4 回答
![?](http://img1.sycdn.imooc.com/545862aa0001f8da02200220-100-100.jpg)
TA贡献1880条经验 获得超4个赞
那是因为该Scanner.nextInt
方法没有读取通过点击“Enter”创建的输入中的换行符,因此Scanner.nextLine
在读取该换行符后返回调用。
当您使用Scanner.nextLine
after Scanner.next()
或任何Scanner.nextFoo
方法(nextLine
自身除外)时,您将遇到类似的行为。
解决方法:
要么把一个
Scanner.nextLine
电话后,每Scanner.nextInt
或Scanner.nextFoo
消耗该行包括休息换行符int option = input.nextInt();input.nextLine(); // Consume newline left-overString str1 = input.nextLine();
或者,更好的是,通过读取输入
Scanner.nextLine
并将输入转换为您需要的正确格式。例如,您可以使用Integer.parseInt(String)
方法转换为整数。int option = 0;try { option = Integer.parseInt(input.nextLine());} catch (NumberFormatException e) { e.printStackTrace();}String str1 = input.nextLine();
![?](http://img1.sycdn.imooc.com/545863e80001889e02200220-100-100.jpg)
TA贡献1874条经验 获得超12个赞
问题在于input.nextInt()方法 - 它只读取int值。因此,当您继续使用input.nextLine()读取时,您会收到“\ n”Enter键。所以要跳过这个,你必须添加input.nextLine()。希望现在应该清楚这一点。
试试这样:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
![?](http://img1.sycdn.imooc.com/533e4c2300012ab002200220-100-100.jpg)
TA贡献1877条经验 获得超6个赞
这是因为当你输入一个数字然后按Enter,input.nextInt()
只消耗数字,而不是“行尾”。当input.nextLine()
执行时,它会消耗来自第一输入缓冲器中的“行结束”静止。
相反,请input.nextLine()
立即使用input.nextInt()
添加回答
举报