My input is in this format:
1 2 3 4 5 6
Alice
The array length is not known. I coded it this way:
import java.util.*;
public class Main
{
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int i=0;
while(sc.hasNext()){
arr.add(sc.nextInt());
}
String player = sc.nextLine();
}
}
But I am getting this error.
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:17)
Thanks in advance.
CodePudding user response:
You should use hasNextInt
to check for integer input. Once no more integers, then just use next()
to read the player.
List<Integer> arr = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt()){
arr.add(sc.nextInt());
}
String player = sc.next();
arr.forEach(System.out::println);
System.out.println(player);
Example input's supported
10 20 30 40 50 60 70
Alice
10 20 30 40
50 60 70 Alice
10 20 30
40
50
60 70 Alice
10 20 30
40 50
60 70
Alice
output
10
20
30
40
50
60
70
Alice
CodePudding user response:
The reason you are seeing java.util.InputMismatchException
is because you provided input "Alice" to the statement sc.nextInt()
, and the scanner is telling you that it doesn't know how to convert a java.lang.String
input to an int (which is the return type of nextInt()
).
Here's a very simple example that reproduces the same behavior:
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
If you run those two lines and enter a non-integer, like "d", it will throw an exception:
d
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at a91.main(a91.java:6)
To fix it, you need to replace nextInt()
with something that is tolerant of non-numeric input, possibly nextLine()
. Here is a (very) simple example showing how that could work. Note this is just highlighting the behavior you're asking about, namely: how to address InputMismatchException
. As with your original program, there is no loop termination – it will run forever (until you quit the program).
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
while (sc.hasNext()) {
String s = sc.nextLine();
System.out.println("got this: " s);
}
1 2 3 4 5 6
got this: 2 3 4 5 6
Alice
got this: Alice