Simple Java Query - Getting a Result from a Integer
I have been set an assignment where I must find the average of a list of positive numbers enterd by the user, the amount of numbers entered is unknown. So far I have got the program to add all numbers that have been entered (the entry teminates when a user enters 0). I do not want the answer to this question on here because I am really trying to learn this fast!
I am having trouble with the while statement,
I wanted to say
WHILE ( numberentered = 0 );
......
but this doesnt seem to work
I originally did it like so:
while ( numberentered >= 1 );
System.out.print (numbersum);
but this still jumps out of the do loop when a negative number is entered.
Any 开发者_StackOverflowidea guys.... If you understand my question but it is still worded very badly... please edit.
Thank you.
while (numberentered != 0) { < read new number and add it to total and ... (but you didn't want the answer...) > }
Shouldn't you be doing this?
while(numberEntered != 0) {
// add it up
}
It seems like maybe you meant to do:
while (numberentered != 0) {
//do stuff
}
Note that no semicolon is needed on the 'while' line itself.
This is what I interpreted the problem statement:
"User is allowed to enter the numbers as many times but when it enters 0, the program would display the average of the numbers being entered prior to 0 and exit"
You may go this way:
public static void main(String args[]) {
float no = 0;
float average = 0;
int count = 1;
if(args.length == 0) {
printf("No number being entered...program exits");
System.exit(0);
}
if(args[0] == 0) {
displayAverage(average);
return;
}
for(count;count<args.length;count++){
try {
no = Float.parseFloat(args[count]);
if(no == 0 ) {
break;
}
average = average + no;
}
catch(NumberFormatException nfe) {
printf("Please enter only numbers");
}
}
average = average/count;
printAverage(average);
}
private void displayAverage(float average){
System.out.println("average is: "+ average);
}
hope this may helps..
精彩评论