我无法弄清楚我的代码中的 "Java InputMismatchException errors"

I can't figure out the "Java InputMismatchException errors" in my code

在我的代码中,我使用“\n”作为分隔符,因为用户输入的字符串中可能有一些'sapce'。但是有一个例外 appeared.I 我是 Java 的新手,我是 confused.So 非常感谢你帮助我。

我的代码是:

import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] args) {

        Scanner scanner=new Scanner(System.in);
        scanner.useDelimiter("\n");

        System.out.print("Please enter your ID:");
        int id=scanner.nextInt();
        System.out.print("Please enter your address:");
        String address=scanner.next();
    }

}

并且输出:

Please enter your ID:20151212
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at learning.ScannerDemo.main(ScannerDemo.java:12)

如果您仍想使用 \n 作为分隔符,只需在修剪后转换您得到的文本。


解决方案

int id = Integer.valueOf(scanner.next().trim());

或者干脆去掉分隔符。

设置分隔符会导致问题 - nextInt 将“\n”查找为预期格式的一部分,但它已被扫描器使用。

如果您想要一种更适合最终用户的方法,您最好扫描下一个字符串,trim 然后自己将其转换为 Integer。

使用 scanner.nextLine() 然后 trim() 并转换为 int。

由于行终止符因 OS 而异。

  • Windows系统使用“\r\n”
  • Linux系统使用“\n”

因此,如果您 运行 您的代码在 windows 上,您应该使用“\r\n”作为分隔符。 但是 java.

提供了一个更好的选择
System.getProperty("line.separator");

所以你应该使用

scanner.useDelimiter(System.getProperty("line.separator"));