gpt4 book ai didi

java - 为什么 Scanner.next() 不接受键盘输入按下?

转载 作者:行者123 更新时间:2023-12-01 10:25:31 24 4
gpt4 key购买 nike

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;
}
}
}
}

当我运行这段代码时,当按下计算机的回车键时,try-catch block 中的第一个scan.next()没有响应,因此无法输入后续的if()语句。文本字段中的光标仅换行,但输入永远不会被接受。我正在使用 netbean IDE

最佳答案

http://javatutorialhq.com/java/util/scanner-class-tutorial/

nextInt method does not read the last newline character of your input, and thus that newline is consumed in the next call to nextLine. To resolve this just use next instead of nextline but if you insist of using nextLine add another scan.nextLine() after nextInt. Take a look below snippet

-> 在 scan.nextInt() 之后添加 scan.nextLine()

关于java - 为什么 Scanner.next() 不接受键盘输入按下?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35374367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com