Reputation: 139
I would like to have the user input a line of text as long as x
is not equal to the value of numOfContestans
. When I run the code, I get an InputMismatchException
. Does anyone have an idea on how to solve this error?
try {
int numOfContestants = scan.nextInt();
int problems = scan.nextInt();
scan.nextLine();
int x = 0;
while (x != numOfContestants) {
String input = scan.nextLine();
x++;
}
System.out.println(problems);
} catch(InputMismatchException e) {
System.out.println("Something went wrong");
}
Upvotes: 0
Views: 259
Reputation: 1306
You do not list the input that causes a problem. If you try this input,
3
2
line1
line2
line3
nextInt does not read the CR/LF at the end of the line. The first call to nextLine is empty. The loop runs the correct amount of times, but the first pass does not read a complete line. After reading the problems, read the next line.
int problems = scan.nextInt();
String input = scan.nextLine();
You could also enter you data so it looks like
3
2 line1
line2
line3
Then your code works.
I could not generate an error, as long as the intergers were entered properly.
I do not know how nextLine could cause a TypeMismatchException. I have run this code and can only cause such an error if an integer is entered incorrectly. Please provide the input that causes the error.
Upvotes: 1