sc.nextLine() 抛出 InputMismatchException,而 sc.next() 不会

sc.nextLine() throws InputMismatchException while sc.next() doesn't

提问人:Programmer AHN 提问时间:7/27/2023 更新时间:7/27/2023 访问量:52

问:

在下面的代码片段中,在我输入 coach 的值并按 Enter 键后,扫描仪正在抛出。但是,如果我使用 ,则不会抛出此类异常。InputMismatchExceptioncoach=sc.next();

void accept() {
        System.out.println("Enter name , mobile number and coach for the customer and also the amount of ticket.");
        name=sc.nextLine();
        mobno= sc.nextLong();
        coach=sc.nextLine();
        amt=sc.nextInt();
    }

我预计在这两种情况下都不会出现异常,但是我不明白为什么仅针对 . 谢谢大家!sc.nextLine();

java.util.scanner 输入MismatchException

评论

1赞 dan1st 7/27/2023
确切的输入是什么?
3赞 7/27/2023
到目前为止,您的错误描述和调试不是很详细,但这可能是在 nextLong() 调用后跳过 nextLine() 的情况
0赞 Sören 7/27/2023
这回答了你的问题吗?扫描仪在使用 next() 或 nextFoo() 后跳过了 nextLine()?

答:

2赞 Diego Borba 7/27/2023 #1

当您调用读取 Coach 时,它会遇到上一次调用留下的换行符。因此,它会读取一个空行(将换行符解释为输入行)并继续操作,而不允许您输入教练名称sc.nextLine()nextLong()

我的建议是始终使用并转换为想要的,如下所示:nextLine()Class

void accept() {
    System.out.println("Enter name , mobile number and coach for the customer and also the amount of ticket.");
    name = sc.nextLine();
    
    // Cast long value
    mobno = Long.valueOf(sc.nextLine());
    
    coach = sc.nextLine();
    
    // Cast int value
    amt = Integer.parseInt(sc.nextLine());
}

看看这个:

但你也可以这样做:

void accept() {
    System.out.println("Enter name, mobile number, coach for the customer, and also the amount of ticket.");
    name = sc.nextLine();
    mobno = sc.nextLong();

    // Consume the remaining newline character in the input buffer
    sc.nextLine();

    coach = sc.nextLine();
    amt = sc.nextInt();
}

评论

0赞 Programmer AHN 7/27/2023
谢谢,它有效!
1赞 Diego Borba 7/27/2023
@ProgrammerAHN 不客气!