I've attached the following portion of my code. Currently if i enter a string value such as 'a' it will fall into the first if statement and print out 'INPUT' which I used to identify the problem. This later causes a problem as when the value for group1 is always too high.
To solve this I created the 'invalidInput' variable and decrease this by 1 every time a string is entered and later add this value to group1. However I think this is a bad way to go about it and I don't know where the error lies.
Scanner in = new Scanner(System.in);
System.out.println("Enter test scores: ");
// Check type is integer
if (in.hasNextInt()) {
int marks = in.nextInt();
//Only updates total, max and min if the input is within valid range
if ((marks > -1) && (marks < 101)) {
total = total + marks;
max = marks;
min = marks;
}
// Check for sentinal value
while (marks != -1) {
// Assign marks to specific group and increment counter
if ((marks >= 0) && (marks <= 29)) {
group1++;
System.out.println("INPUT");
System.out.println(group1 + " GROUP1");
} else if ((marks >= 30) && (marks <= 39)) {
group2++;
} else if ((marks >= 40) && (marks <= 69)) {
group3++;
} else if ((marks >= 70) && (marks <= 100)) {
group4++;
} else {
System.out.println("Invalid score");
}
if (in.hasNextInt()) {
marks = in.nextInt();
if ((marks > max) && (marks < 101)) {
max = marks;
}
if ((marks < min) && (marks > -1)) {
min = marks;
}
total = total + marks;
}
/* Prints out an error message if invalid input. Stores
this in an unused variable to avoid infinite loop. Decreases
invalidInput by 1 which is later added on to studentsTotal to make
sure the average is only calculated from valid input. Also ensures the total
number of student scores entered only counts valid input.
*/
else {
//System.out.println("Invalid score");
String x = in.next();
//invalidInput --;
}
}
Aucun commentaire:
Enregistrer un commentaire