文件中的扫描仪InputMismatchException [英] Scanner InputMismatchException from file
本文介绍了文件中的扫描仪InputMismatchException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Java做我的第一步,这是我的问题:
Doing my first steps with Java, here's my problem:
1.)可以读取rawData.txt
:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import static java.lang.System.out;
class ReadAndWrite {
public static void main(String args[])
throws FileNotFoundException {
Scanner diskScanner = new Scanner(new File("rawData.txt"));
String diskString;
diskString = diskScanner.nextLine();
out.println(diskString);
diskScanner.close();
}
}
eclipse控制台中的结果是:
The result in eclipse console is :
>19.5 5
所以我想内容可以阅读.
So I guess the content can be read.
但是:nextDouble()
和nextInt()
不起作用:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class ReadAndWrite {
public static void main(String args[])
throws FileNotFoundException {
Scanner diskScanner = new Scanner(new File("rawData.txt"));
double unitPrice, quantity;
unitPrice = diskScanner.nextDouble();
quantity = diskScanner.nextInt();
[...]
diskScanner.close();
}
}
控制台发出的错误消息是:
The error message from console is:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at ReadAndWrite.main(ReadAndWrite.java:16)
那我该怎么做才能理解这个问题?
So what can I do to understand the problem?
推荐答案
我刚刚在计算机上进行了测试,发现了问题所在.预期的double
格式取决于Locale
.在某些国家/地区,小数位数用,
分隔,而有些则用.
.
I have just made a test on my machine and I've found the problem. Expected double
format depends on Locale
. In some countries the decimal digits are separated with ,
and some with .
.
Scanner diskScanner = new Scanner(new File("rawData.txt")).useLocale(Locale.ENGLISH);
将解决问题.否则,请从以下位置更改文件
will solve the problem. Otherwise change your file from
19.5 5
到
19,5 5
这篇关于文件中的扫描仪InputMismatchException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文