Tri*_*7er 2 java file-io java.util.scanner
我正在尝试读取一个文本文件,然后使用Java中的nextInt()函数在循环中打印出整数.我的文本文件的格式如下:
a 2000 2
b 3000 1
c 4000 5
d 5000 6
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
public static void main(String[] args) throws FileNotFoundException {
String fileSpecified = args[0] + ".txt";
FileReader fr = new FileReader(fileSpecified);
BufferedReader br = new BufferedReader (fr);
Scanner in = new Scanner (br);
while (in.hasNextLine()) {
System.out.println ("next int = " + in.nextInt());
}
}
Run Code Online (Sandbox Code Playgroud)
我总是得到的错误是:
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)
Run Code Online (Sandbox Code Playgroud)
每次在任何程序中使用nextInt()时都会出现此错误.
我认为它将找到字符,例如"a","b","c"这是一个字符串,并且未能将其作为int.您可以通过调试来解决这个问题:
System.out.println ("next value= " + in.next());
//System.out.println ("next int = " + in.nextInt());
Run Code Online (Sandbox Code Playgroud)
您也可以使用API保护来防止这种情况
if(in.hasNextInt()) {
System.out.println ("next int = " + in.nextInt());
}
Run Code Online (Sandbox Code Playgroud)