The following program i wrote for a class activity to prompt the user for a infinite amount of test marks between 0 - 100 and when a user enters a mark outside that range it should tell the user that its invalid(which works so far in my program). When the user enters "-1" its should stop the program and then print out the average of those marks.
import java.util.*;
public class HmWk62 {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int count=1;
int mark, total=0;
double average;
System.out.println("please enter mark "+count);
mark = console.nextInt();
count++;
while ((mark >= 0)&&(mark <= 100)){
System.out.println("Please enter mark "+count);
mark = console.nextInt();
total += mark ;
++count;
while ((mark < 0)||(mark > 100)){
System.out.println("Invalid mark, please re-enter");
mark = console.nextInt();
}
}
}
}
When the user enters "-1" its should stop the program and then print out the average of those marks.
Well if the user enters -1, you'll never get out of the nested loop that validates the input.
If you want to allow -1, you should changed the condition in the nested loop to allow it:
while (mark < -1 || mark > 100)
Also note that you're using the value of mark
before you validate it - so if you enter 10000, you'll still add 10000 to total
before you then ask for a new value - and you'll then ignore the new value.
Also, you're not using the first value of mark
entered at all, other than to see whether or not you should enter the loop.
I suspect you actually want something like:
while (true) {
int mark = readMark(scanner, count);
if (mark == -1) {
break;
}
count++;
total += mark;
}
// Now print out the average, etc
...
private static int readMark(Scanner scanner, int count) {
System.out.println("Please enter mark " + count);
while (true) {
int mark = scanner.nextInt();
if (mark >= -1 && mark <= 100) {
return mark;
}
System.out.println("Invalid mark, please re-enter");
}
}
See more on this question at Stackoverflow