Java 扫描仪没有扫描所有字段?
我在写我的第一个,如果算上hello world的话,是第二个程序,遇到了一个小问题 我的代码:Java 扫描仪没有扫描所有字段?,java,Java,我在写我的第一个,如果算上hello world的话,是第二个程序,遇到了一个小问题 我的代码: import java.util.*; class test { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("What is your name: "); String name = scan.nextLine();
import java.util.*;
class test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("What is your name: ");
String name = scan.nextLine();
System.out.print("What is your favorite number: ");
int favoriteNumber = scan.nextInt();
System.out.print("What is your favorite game: ");
String game = scan.nextLine();
}
}
因此,它扫描名称和favoriteNumber,但程序在要求用户输入喜爱的游戏之前结束。基本上,用户只能输入两次文本,而不是像我希望的那样输入三次。必须在这里抛出异常scan.nextInt();
检查是否输入了正确的int只是猜测:
scan.nextInt()
在用户按enter键后不会使用尾随的换行符。随后对scan.nextLine()
的调用发现一个换行符正在等待
尝试关闭int-favoriteNumber=scan.nextInt()代码>用于字符串favoriteNumber=scan.nextLine()
以查看这是否解决了问题。如果是的话,我的假设是正确的
如果是这种情况,那么您可能应该使用Integer.parseInt
将此字符串转换为整数。这里的问题实际上是您确实想要收集3行输入,其中一行定义为“以换行符结尾的任何字符序列”。您的程序当前编写为请求一行,一个int,然后一行,而不是“3行输入,其中一行包含int”。+1另一种方法是在nextInt()之后调用scan.nextLine()
来使用剩余的新行标记(这种方法不如int-favoriteNumber=Integer.parseInt(scan.nextLine())
那么清晰,但有助于确认问题的根源)。确实,这可能是一个很好的简单解决方案。