im new to java and need help with this code. i need to show stars to represent the numbers which have been entered. so far my for loop is only showing the one star, how can i get it to show the number of stars which represent the amount of numbers i have entered.

System.out.println("Enter Student mark");
number = Integer.parseInt(br.readLine());
if (number <=29)
bottom = bottom + 1;
else if (number >=30 && number <=39 )
middle = middle + 1;
else if (number >=40 && number <= 69)
middletop = middletop + 1;
else if (number >=70 && number <=100)
top = top + 1;
}

System.out.print("0-29 " + bottom);
for (star=1; star <= bottom; star++); {
System.out.println("*");
}


if bottom represents five numbers, can anyone help and show how to print five stars to represent bottom.im new to java and dont understand for loops yet.

Recommended Answers

All 4 Replies

for (star=1; star <= bottom; star++); {

Remove the semicolon in this line. Right now your loop is an empty instruction, repeated bottom times, followed by a single println.

If bottom = 5, expected output is '*****'.

String val = "";

for (int star = 0; star < bottom; start++) {
     val = val + "*";
}

System.out.println(val);

thank you. rather than have the system.out.print as val i changed it to a *. as with the sstem.out.print "val". the word val was being printed.

System.out.println("val"); is not the same as System.out.println(val); The first prints the word "val", the second prints the value contained in the variable named val .

Eric's code is good, but he isn't helping you much by not explaining what he's doing. :-/ Look at his code again - instead of creating a line by looping through print statements, he's constructing a String, valled var which has the right number of '*'s in it, and then printing that String.
It's a slightly different approach to the one you're using.

But I have to say, you should not get in the habit of constructing Strings this way. It works, but it's inefficient. Instead, you should use either the StringBuffer or the StringBuilder class for this sort of thing:

StringBuffer val = new StringBuffer("");

for (int star = 0; star < bottom; start++) {
     val.append("*");
}

System.out.println(val.toString());

Get in this habit now. The reason for it has to do with the fact that String objects are "immutable", meaning that they can't be changed. It sounds like you're pretty new to this stuff, so I won't bother you with the details unless you're really curious, but if you're ever assembling a String by putting things together in this fashion, it's better to do it this way.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.