使用扫描仪从文件双精度值读取-InputMismatchException? [英] Reading from file double value using Scanner - InputMismatchException?
本文介绍了使用扫描仪从文件双精度值读取-InputMismatchException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试从文件双精度值中读取数据,并为此目的使用了Scanner
.
I tried read from file double values and using Scanner
with this aim.
它抛出 InputMismatchException
:
"input.txt" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
我不明白为什么会这样?
And I can't understand why this happen?
代码:
public class Largest
{
public static void main(String[] args)
throws FileNotFoundException
{
String filename = "input.txt";
Scanner in = new Scanner(filename);
double largest = in.nextDouble();
while (in.hasNextDouble())
{
double input = in.nextDouble();
if (input > largest)
{
largest = input;
}
}
in.close();
System.out.println("Largest value: " + largest);
}
}
更新:
我尝试将double largest = in.nextDouble();
更改为double largest = 0;
但是输入错误:
UPDATE:
I tried change double largest = in.nextDouble();
to double largest = 0;
But it get wrong input:
filename Actual Expected
-------------------------------------------------------------
"input.txt" Largest value: 0.0 Largest value: 1.343239923E9
"input2.txt" Largest value: 0.0 Largest value: 40.1
文件内容如下:
89343455
46746846
56.78
55486411
如何解决此问题?
推荐答案
我找到了解决方案-需要创建File对象,然后将其提供给扫描程序类:
I found solution - need to create File object and then feed it to scanner class:
String filename = "input.txt";
File newFile = new File(filename);
Scanner in = new Scanner(newFile);
这篇关于使用扫描仪从文件双精度值读取-InputMismatchException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文