如何从文件中读取java中的double

时间:2016-02-18 09:39:01

标签: java double java.util.scanner

我正在尝试从文件中读取双精度但我有这个例外: java.util.InputMismatchException。我试过做useLocale(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);
            ...

    }
}

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

city1 city2 distance(km)

string string double

Barcelona Madrid 3005.15
Barcelona Valencia 750
Los_Angeles Toronto 8026.3
......

3 个答案:

答案 0 :(得分:1)

你可以这样:

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);
}

希望得到这个帮助。

答案 1 :(得分:0)

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

尝试使用此代码:

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 + "'");
        }
    }
}

答案 2 :(得分:0)

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

添加此代码,您的代码应该有效:

fitxer.useLocale(Locale.US);

请注意,您不需要为第一台扫描仪设置Locale,只能传递字符串,而不能使用double格式。