java为什么是扫描仪。下一步()不接受键盘回车键?
import java.util.InputMismatchException;
import java.util.Scanner;
class ClassB {
public static void main(String[]args) throws Exception{
ClassB b = new ClassB();
b.getInput();
}
public void getInput() throws Exception {
String label = null;
int input;
Scanner scan = new Scanner(System.in);
for (input = 1; input != 4; input++){
switch(input){
case 1: label = "name";
break;
case 2: label = "password";
break;
case 3: label = "Room number";
break;
}
System.out.println("Enter your " + label);
scan.next();
try{
if (input == 1){
int name = scan.nextInt();
//residence.changeName(name);
}
else if(input == 2){
String password = scan.next();
}
int rmNumber = scan.nextInt();
}catch (IllegalArgumentException | InputMismatchException me ){
String type = "A string";
String message = (input == 1 || input == 2) ? type : "An integer";
input = 1;
}
}
}
}
当我运行此代码时,第一次扫描。当按下计算机的enter键时,try catch块中的next()不响应,因此无法输入后续的if()语句。文本字段中的光标只换行,但永远不会接受输入。 我正在使用NetBeanIDE
# 1 楼答案
从您的回答来看,您仍然看到它被卡住,并且要求用户多次输入值,我不确定代码的区别是什么。这是我的代码,我用它进行了测试,但没有遇到这个问题(对我来说)
在try/catch if/else语句中,您没有检查条件3。 您被“卡住”的原因是您还第二次调用了nextInt(),导致它在第一次输入房间号后仍等待其他输入。将if条件替换为以下条件,然后重试:
# 2 楼答案
http://javatutorialhq.com/java/util/scanner-class-tutorial/
->;添加扫描。扫描后的下一行()。nextInt()