My input is in this format:
JavaScript
x
1 2 3 4 5 6
Alice
The array length is not known. I coded it this way:
JavaScript
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.
JavaScript
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.
Advertisement
Answer
You should use hasNextInt
to check for integer input. Once no more integers, then just use next()
to read the player.
JavaScript
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
JavaScript
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
JavaScript
10
20
30
40
50
60
70
Alice