本文介绍了扫描器,nextInt和InputMismatchException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图读取一个文本文件,然后使用Java中的nextInt()函数在循环中打印出整数。我的文本文件格式为:$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
d 5000 6
这里是我的代码:
public static void main(String [] args)throws FileNotFoundException {
String fileSpecified = args [0] +.txt;
FileReader fr = new FileReader(fileSpecified);
BufferedReader br = new BufferedReader(fr);
扫描仪输入=新扫描仪(br); (in.hasNextLine()){
System.out.println(next int =+ in.nextInt());
while(in.hasNextLine
$ / code $ / pre
$ b $我得到的错误是:
pre $ 异常在线程mainjava.util.InputMismatchException $ b $在java.util.Scanner.throwFor(未知源)
在java.util.Scanner.next(未知源)$ b $在java.util.Scanner.nextInt(未知源)$ b $在java.util.Scanner.nextInt(未知源)
每当我在任何程序中使用nextInt()时,都会得到这个错误。
while(in.hasNext) ()){
System.out.println(letter =+ in.next());
System.out.println(integer1 =+ in.nextInt());
System.out.println(integer2 =+ in.nextInt());
}
I'm trying to read a text file and then print out the integers in a loop using the nextInt() function in Java. The text file I have is of the form:
a 2000 2
b 3000 1
c 4000 5
d 5000 6
Here is my code:
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());
}
}
The error I always get is:
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)
I get this error everytime I use nextInt() in any program.
解决方案 You probably want something like this instead:
while (in.hasNext()) {
System.out.println("letter = " + in.next());
System.out.println("integer1 = " + in.nextInt());
System.out.println("integer2 = " + in.nextInt());
}
这篇关于扫描器,nextInt和InputMismatchException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!