如何在 java 中从文件中读取双精度



我正在尝试从文件中读取双精度,但我有这个例外:java.util.InputMismatchException. 我尝试使用 locale(Locale.US) 但是它不起作用。

这是我的代码

public static void main(String[] args){
     System.out.println("Introduce the name of the file");
     Scanner teclat = new Scanner(System.in);
     teclat.useLocale(Locale.US);
     Scanner fitxer = new Scanner(new File(teclat.nextLine()));
     while(fitxer.hasNext()){
            String origen=fitxer.next();
            String desti=fitxer.next();
            double distancia=fitxer.nextDouble();
            System.out.println(origen);
            System.out.println(desti);
            System.out.println(distancia);
            ...
    }
}

现在这是我必须阅读的文件的内容。

城市

1 城市2距离(公里)

字符串字符串双精度

Barcelona Madrid 3005.15
Barcelona Valencia 750
Los_Angeles Toronto 8026.3
......
你可以

喜欢这样:

String str = "Barcelona Madrid 3005.15";
double value = Double.parseDouble(str.split(" ")[2]);

或者,如果您想使用正则表达式,您也可以按以下步骤进行操作:

Pattern pattern = Pattern.compile("\d+\.\d+");
Matcher matcher = pattern.matcher("Barcelona Madrid 3005.15");
if (matcher.find()) {
   double value = Double.parseDouble(matcher.group());
   System.out.println("value = " + value);
}

希望这有帮助。

由于元组的起点、目的地和距离在一行中,因此最好先阅读该行,然后再拆分为单词。我在你上一个例子中看到,即使名称有两个部分,它们也是用下划线_而不是空格写的。因此,我们可以安全地与空间分开。

尝试使用以下代码:

import java.io.*;
public class Test {
    public static void main(String [] args) {
        String fileName = "file.txt";
        String line = null;
        try {
            FileReader fileReader = new FileReader(fileName);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            while((line = bufferedReader.readLine()) != null) {
                String[] parts = line.split(" ");
                String origen=parts[0];
                String desti=parts[1];
                double distancia=Double.parseDouble(parts[2]);
                System.out.println(origen);
                System.out.println(desti);
                System.out.println(distancia);
            }   
            bufferedReader.close();         
        }
        catch(FileNotFoundException ex) {
            System.out.println("Unable to open file '" + fileName + "'");                
        }
        catch(IOException ex) {
            System.out.println("Error reading file '" + fileName + "'");
        }
    }
}

您没有为实际读取双精度的第二个Scanner设置Locale

添加这个,你的代码应该可以工作:

fitxer.useLocale(Locale.US);

请注意,您不需要为第一个扫描仪设置Locale,它仅用于传递字符串,而不是处理double格式。

最新更新