So, I have this little program here and I've been getting the input mismatch error. I'll post the error message below the code. To be honest, I have 0 clue why the error appears. I've checked that all the required variables have correct type assigned. If I understand correctly, the said error happens when you try to input something that is not expected, right? ( double instead of int or whatever). I probably did some stupid mistake somewhere that I cant see for some reason, so I'd appreciate your help.
Scanner sc = new Scanner(System.in);
int enEur = 0;
int dvaEur = 0;
boolean bankrot = false;
int placilo;
while (sc.hasNextInt() || bankrot == false){
placilo = sc.nextInt();
if(placilo == 1){
enEur += placilo;
}
else{
enEur --;
bankrot = test(enEur);
dvaEur ++;
}
}
So, this is the content of my main() method. The error appears in the line: placilo = sc.nextInt(). Here's the copy of the said error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at evroSop.main(evroSop.java:16)
The input that I put in is basically a line of separate integers like: 1 1 1 1 2 1... and so on. I've got different examples, all of which are lines of integers of different lengths.
Cherio, George
Read the line as String and split it into int[]
after hasNext() call,
and split this String into int[]
Example code:
Input:
Output:
1
123
456
The condition
while (sc.hasNextInt() || bankrot == false)
means that you'll continue trying to read from the scanner as long as there is more input orbankrot
is still false. So, if you run out of inputs and still aren't bankrupt, you'll get an exception because you'll try reading next input even though there is no more of it.The condition should be and, not or, probably.