[英]I can't figure out the “Java InputMismatchException errors” in my code
在我的代码中,我使用“ \\ n”作为分隔符,因为用户的输入字符串中可能有一些“空格”。 但是出现了一个例外,我是Java的新手,我很困惑,所以我非常感谢您的帮助。
我的代码是:
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”作为预期格式的一部分进行查找,但扫描仪已将其使用。
如果您想使用一种更适合最终用户的方法,最好扫描下一个字符串,修剪它并自己转换为Integer。
使用scanner.nextLine(),然后使用trim()并转换为int。
由于行终止符随OS的不同而不同。
因此,如果您在Windows上运行代码,则应使用“ \\ r \\ n”作为分隔符。 但是java提供了一个更好的选择。
System.getProperty("line.separator");
所以你应该使用
scanner.useDelimiter(System.getProperty("line.separator"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.