我调用了一个扫描对象,使用我试图从用户那里获取一个 int 和一个字符串的相同对象。
Scanner scan = new Scanner(System.in);
//for a int
int first_value = scan.nextInt();
System.out.println(first_value);
//for a string
String first_name = scan.nextLine();
System.out.println(first_name);
这里控制台不等待字符串,但如果我使用另一个对象,那么它工作正常。
Scanner insert = new Scanner(System.in);
String name = insert.nextLine();
是否可以使用相同的 Scanner 对象获取 int 和 string ?
最佳答案
那是因为读取 int 后留下了一个 new line
字符,该字符被您的 scan.nextLine
消耗,并且它没有等待您的下一个输入。您需要在读取字符串之前使用它。
Scanner scan = new Scanner(System.in);
//for a int
int first_value = scan.nextInt();
scan.nextLine();
System.out.println(first_value);
//for a string
String first_name = scan.nextLine();
System.out.println(first_name)
关于java - 为什么在java中我们不能通过一个扫描器对象获取用户输入的int和string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37936661/