0

In my code,I use "\n" as the delimiter, because there may be some 'sapce' in the user's input string. But a exception appeared.I am new to Java and I'm confused.So I'm very grateful to you for helping me out.

My code is:

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

}

And the output:

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)
4

4 回答 4

1

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


解决方案

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

或者干脆去掉分隔符。

于 2015-12-12T14:14:44.013 回答
0

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

于 2015-12-12T14:25:36.517 回答
0

由于行终止符因操作系统而异。

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

因此,如果您在 Windows 上运行代码,则应使用“\r\n”作为分隔符。但是java提供了一个更好的选择。

System.getProperty("line.separator");

所以你应该使用

scanner.useDelimiter(System.getProperty("line.separator"));
于 2015-12-12T14:56:18.253 回答
0

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

如果您想要一种对最终用户更友好的方法,您最好扫描下一个字符串,修剪它并自己将其转换为 Integer。

于 2015-12-12T14:17:57.123 回答