我正在练习扫描仪的使用和语法,下面是我编写的代码,我试图从用户那里获取 4 个输入:
Scanner s= new Scanner(System.in);
int a = s.nextInt();// taking an integer as input, it works fine.
String b = s.nextLine();//was supposed to take a string input, but not working
String c=s.nextLine();//takes a string as input from user
String d=s.nextLine();//takes another string as input from user
System.out.println("integer entered: "+a);
System.out.println("first string entered: "+b);
System.out.println("second string entered: "+c);
System.out.println("third string entered: "+d);
但是用户只能提供 3 个输入,第一个整数和其他两个字符串输入,并且通过打印这 4 个变量的值,很明显第一个字符串的输入 String b
被跳过。然后我尝试重新排列输入的顺序,即
String b = s.nextLine();//takes a string input
int a = s.nextInt();// taking an integer as input
String c=s.nextLine();//was supposed to take a string as input from user
String d=s.nextLine();//takes another string as input from user
在本例中,第二个字符串的输入 String c
被跳过。
那么,是不是因为整数输入而跳过了下一个字符串输入呢?
最佳答案
这是一个常见问题。
<小时/>固定代码
Scanner s= new Scanner(System.in);
int a = s.nextInt();
s.nextLine();
System.out.print("Enter a string: ");
String b = s.nextLine();
System.out.print("Enter another string: ");
String c=s.nextLine();
System.out.print("Enter one more string: ");
String d=s.nextLine();
System.out.println(a+"\n"+b+d+c);
引用: Scanner is skipping nextLine() after using next() or nextFoo()?
关于java - 当字符串变量的输入前面有整数输入时,该输入将被跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60763449/