为什么在java中我们可以';t通过一个扫描对象获取用户输入的int和string?
我调用了一个扫描对象,使用的是我试图从用户那里获取的同一个对象,一个int和一个字符串为什么在java中我们可以';t通过一个扫描对象获取用户输入的int和string?,java,Java,我调用了一个扫描对象,使用的是我试图从用户那里获取的同一个对象,一个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 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();
是否可以使用相同的扫描对象获取int和string 这是因为在读取int之后,留下了一个
新行
字符,该字符被您的扫描.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)
这是因为在读取int之后,留下了一个
新行
字符,该字符被您的扫描.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)
使用
System.out.println(“输入您的年龄”)
和System.out.println(“输入您的姓名”)代码>在通过扫描仪
对象获取用户输入之前
System.out.println("Enter your first name:");
String first_name = scan.nextLine();
System.out.println("Enter your age:");
int age = Integer.parseInt(scan.nextLine());
现在,它使您能够保持屏幕,以便向程序输入输入内容
使用System.out.println(“输入您的年龄”)
和System.out.println(“输入您的姓名”)代码>在通过扫描仪
对象获取用户输入之前
System.out.println("Enter your first name:");
String first_name = scan.nextLine();
System.out.println("Enter your age:");
int age = Integer.parseInt(scan.nextLine());
现在,它使您能够保持屏幕,以便向程序输入输入内容
因为新行字符缓冲在扫描仪中,而不是在系统中。因此,如果您尝试使用其他扫描仪读取新行字符,它将等待您的输入。因为新行字符缓冲在扫描仪中,而不是在系统中。因此,如果您尝试使用其他扫描仪读取新行字符,它将等待您的输入。