Skip to content
Advertisement

How to take input in java where array length is not defined?

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.

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement