2012-07-12 137 views
0

可能重复:
java, programm not stopping for scan.nextLine()Java scan.nextLine()仅等待用户输入int用户输入;不等待字符串用户输入

System.out.println("Welcome to the Tuition Calculator Program."); 
    System.out.println("How many total credits are you taking?"); 
    credits = scan.nextInt(); 

    System.out.println("Are you a Washington resident? y/n"); 
    resident = scan.nextLine(); 

    System.out.println("Are you a graduate student? y/n"); 
    grad = scan.nextLine(); 

我新的Java和相对较新的编程。在使用jGRASP的个人电脑上。在上面的代码中,我只需要用户输入学分数(int响应),居住(字符串)和毕业生状态(字符串)。

它允许用户输入学分,但是一起打印居民问题和毕业生问题。它不会停止并允许用户输入对居住问题的答案。 (它的确允许我输入我对毕业生问题的回答。)

这个论坛上的其他相关问题没有帮助;我已经尝试添加额外的行来吞下任何额外的换行符,但那还没有完成。也许我添加了错误的类型。 This thread很有帮助,但没有提供可行的解决方案。

+0

链接线程中的答案完全正确。到处使用'nextLine'和'Integer.parseInt'来转换为整数。 – 2012-07-12 03:07:15

回答

1

这是为什么发生?
如果您尝试打印resident,您会发现它会打印newline字符。 其实这里发生的是这个。输入credits后输入的字符串被复制到resident变量中。所以你需要的是避免换行符。

使用nextLine()并解析它使用Integer.parseInt()整数读取credits

System.out.println("Welcome to the Tuition Calculator Program."); 
    System.out.println("How many total credits are you taking?"); 
    credits = Integer.parseInt(scan.nextLine()); 
    System.out.println("Are you a Washington resident? y/n"); 
    resident = scan.nextLine(); 
    System.out.println("Are you a graduate student? y/n"); 
    grad = scan.nextLine(); 
+0

谢谢cdev,这是一个很好的解释。这里类似问题的答案似乎表明,从int用户输入切换到字符串用户输入时,总会发生这种情况。我会注意的。 – user1519533 2012-07-12 04:32:43