Different Java Scanner for input of different types

后端 未结 5 518
不思量自难忘°
不思量自难忘° 2021-01-16 06:40

Imagine the following scanario: I have a program which ask for an integer input, followed by a String input.

int age=0;
String name;
Scanner sc = new Scanne         


        
5条回答
  •  旧时难觅i
    2021-01-16 07:15

    You should use only one Scanner instance per object that you are scanning. In this case you are reading from the System.in, so opening two scanners on the same them concurrently does not even make sense.

    So you definately want to go with your first option, then the question comes, what is wrong with it:

    Well, you ask for sc.nextInt(), an integer, and a name rarely is an integer. You are most likely looking for either name = sc.next() for one word or for name = sc.nextLine() for a whole sentence (until the enter key has been pressed).

    Also be aware that after sc.nextInt(), actually after any sc.next***(), you need to press Enter.

提交回复
热议问题