This is a piece of code from a project I'm working on that prompts the user to pick a number of students between 1 and 10, and a score between 1 and 100 for each of the n number of students. If the user inputs a number of students or a score that is out of the range, an error message pops up and they will be prompted to input this/these bad value(s) again.
Picking the number of students is simple enough, and the code here works perfectly fine, mostly because it doesn't involve a loop to check the value (only 1 int).
The "scores" portion of the code (beginning with scores = new double[]) must have a boolean named errFlag that controls the while loop, an inner for loop, and if/else if statements. This code works as well, but the inner "for" loop causes the error in the "else if" statement:
System.out.println("ERROR: Enter number(s) in the range of 0-100!");
System.out.println("ERROR: Enter all " + (numStudents) + " scores again: ");
to print as many times as numStudents (ie 2 students inputted, error lines print twice). I only want this error to print once if any of the values inputted are out of bounds (1-100). Is there any way I can control the loop to only print this error out once no matter how many times the loop executes?
boolean errFlag = false; final int MIN = 0; final int MAX = 100; final int MAX_STUDENTS = 10; do{ //prompt user for number of students between 1 and 10 System.out.print("Enter number of students("); System.out.println((MIN + 1) + "-" + (MAX_STUDENTS + "): ")); numStudents = scan.nextInt(); //keep prompting user for number of students until they pick one between 1 and 10 if(numStudents > MAX_STUDENTS) { do { System.out.println("Error: Enter an integer in the range of 1-10!"); System.out.print("Enter number of students("); System.out.println((MIN + 1) + "-" + (MAX_STUDENTS + "): ")); numStudents = scan.nextInt(); }while(numStudents > MAX_STUDENTS); } //prompt the user for scores for each of these students until all five are between 1 and 100 scores = new double[numStudents]; System.out.print("Enter " + (numStudents) + " scores("); System.out.println((MIN) + "-" + (MAX + "): ")); while(errFlag = false); { for(int i = 0; i < numStudents; i++) { tmp = scan.nextDouble(); if(tmp >= MIN && tmp <= MAX) { scores[i] = tmp; errFlag = true; } else if(tmp < MIN || tmp > MAX) { System.out.println("ERROR: Enter number(s) in the range of 0-100!"); System.out.println("ERROR: Enter all " + (numStudents) + " scores again: "); i--; errFlag = false; } } }