Jammoy Jammoy - 7 days ago 5
Java Question

Need help in histogram displaying the stars

I need help with displaying the stars for each cat1 to cat4. the problem I'm having is, the stars are being displayed below the cat1 to cat4 when you run the code. I want the stars to be displayed at the side of each cat.

The output of my coding is:

Read in a mark
21

Enter the next student mark
2

Enter the next student mark
30

Enter the next student mark
31

Enter the next student mark
40

Enter the next student mark
41

Enter the next student mark
70

Enter the next student mark
71

Enter the next student mark
109 = when the person enters a number over 100 the while loop ends.

Total number of marks entered 8

0-29: 2

*

*

30-39: 2

*

*

40-69: 2

*

*

70-100: 2

*

*

what I expected the coding to look like :
0-29:
*
*

30-39:
*
*

40-69:
*
*

70-100:
*
*

int cat1 = 0;
int cat2 = 0;
int cat3 = 0;
int cat4 = 0;
int mark;
int counter = 0;

Scanner input = new Scanner(System.in);
System.out.println("Read in a mark");
mark = input.nextInt();

while (mark <= 100 && mark >= 0) {
counter++;
if (mark >= 0 && mark <= 29) {
cat1++;
}
if (mark >= 30 && mark <= 39) {
cat2++;
}
if (mark >= 40 && mark <= 69) {
cat3++;
}
if (mark >= 70 && mark <= 100) {
cat4++;
}

System.out.println("Enter the next student mark");
mark = input.nextInt();
}
System.out.println("Total number of marks entered " + counter);

System.out.print("");
System.out.println("0-29: " + cat1);
for (int i = 0; i < cat1; i++) {
System.out.println("*");
}
System.out.print("");
System.out.println("30-39: " + cat2);
for (int i = 0; i < cat2; i++) {
System.out.println("*");
}
System.out.print("");
System.out.println("40-69: " + cat3);
for (int i = 0; i < cat3; i++) {
System.out.println("*");
}
System.out.print("");
System.out.println("70-100: " + cat4);
for (int i = 0; i < cat4; i++) {
System.out.println("*");
}

Answer

You should change System.out.println to System.out.print and add a System.out.println(); at the end after each loop

System.out.print("");
System.out.print("0-29: " + cat1);
for (int i = 0; i < cat1; i++) {
    System.out.print("*");
}
System.out.println();
System.out.print("");
System.out.print("30-39: " + cat2);
for (int i = 0; i < cat2; i++) {
    System.out.print("*");
}
System.out.println();
System.out.print("");
System.out.print("40-69: " + cat3);
for (int i = 0; i < cat3; i++) {
    System.out.print("*");
}
System.out.println();
System.out.print("");
System.out.print("70-100: " + cat4);
for (int i = 0; i < cat4; i++) {
    System.out.print("*");
}
System.out.println();

probably you should also add some white spaces where needed