0

我尝试从文件中读取双精度值并Scanner以此为目标使用。

它抛出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)

我不明白为什么会这样?

代码:

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;
但输入错误:

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

如何解决这个麻烦?

4

3 回答 3

1

我找到了解决方案 - 需要创建 File 对象,然后将其提供给扫描仪类:

String filename = "input.txt"; 
File newFile = new File(filename);
Scanner in = new Scanner(newFile);
于 2013-07-01T19:04:21.133 回答
0
  • 将最大初始化为第一个双精度(检查类型后)
  • 使用正确的分隔符来解析您的输入(\n= 换行符)

    String filename = "input.txt"; 
    Scanner in = new Scanner(filename).useDelimiter("\\n");
    
    double largest;
    if (in.hasNextDouble())
        largest = in.nextDouble();
    
    while (in.hasNextDouble())
    {
        double input = in.nextDouble();
        if (input > largest)
        {
            largest = input;
        }
    }
    
于 2013-07-01T15:02:25.297 回答
0

尝试这个

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner;

public class MainClass{
public static void main(String[] args)
        throws FileNotFoundException
{
    Scanner in = new Scanner(new File("D:\\input.txt"));
    String largestNum=in.next().trim();
    double largest = Double.parseDouble(largestNum);
    while (in.hasNextDouble())
    {
        String Num=in.next().trim();
        double input = Double.parseDouble(Num);
        if (input > largest)
        {
            largest = input;
        }
    }
    in.close();
    System.out.println("Largest value: " + largest);
} }
于 2013-07-01T15:11:10.363 回答