Search code examples
javastringinputintsentence

How to get multiple inputs using scanner in Java?


This is the input of the program.

3

1 45 5 3 5 Fizz Buzz FizzBuzz Nil

4 13 10 2 7 Ba Bi Be Bu

49 23 5 5 10 Oong Greeng Kattu Eswah

I want to get all these lines as input using Scanner and separate them into Integers and Strings. It is not compulsory to use the scanner. Some other method is also accepted.


Solution

  • Scanner scan = new Scanner("3\n" +
            "\n" +
            "1 45 5 3 5 Fizz Buzz FizzBuzz Nil\n" +
            "\n" +
            "4 13 10 2 7 Ba Bi Be Bu\n" +
            "\n" +
            "49 23 5 5 10 Oong Greeng Kattu Eswah");
    
    ArrayList<String> strings = new ArrayList<>();
    ArrayList<Integer> ints = new ArrayList<>();
    while(scan.hasNext()){
        String word=scan.next();
        try {
            ints.add(Integer.parseInt(word));
        } catch(NumberFormatException e){
            strings.add(word);
        }
    }
    
    scan.close();
    
    System.out.println(ints);
    System.out.println(strings);
    

    If you want Scanner scan input from console with System.in then you need some trigger word which will end loop, for example if("exit".equals(word)) break;.