java sc.next Line()抛出InputMismatchException,而sc.next()不抛出

djp7away  于 2023-08-02  发布在  Java
关注(0)|答案(1)|浏览(112)

在下面的代码片段中,在我输入coach的值并按enter之后,scanner抛出了InputMismatchException。但是如果我使用coach=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();抛出异常。谢谢大家!

igsr9ssn

igsr9ssn1#

当您调用sc.nextLine()来读取coach时,它会遇到上一次nextLong()调用留下的换行符。因此,它读取一个空行(将换行符解释为输入行),并继续执行,而不允许您输入 coach name
我的建议是始终使用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();
}

相关问题