如何从文件中读取Java中的double [英] How to read double in java from a file

查看:317
本文介绍了如何从文件中读取Java中的double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从文件中读取双精度字,但有一个例外:
java.util.InputMismatchException。我尝试做useLocale(Locale.US),但
无效。

I'm trying to read a double from a file but I have this exception: java.util.InputMismatchException. I've tried to do the useLocale(Locale.US) but it doesn't work.

这是我的代码

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

    }
}

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

Now here is the content of the file that I have to read.

city1 city2距离(km)

city1 city2 distance(km)

字符串字符串double

string string double

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

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

Or if you want to use regex you also can do it as below:

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

希望这项帮助。

这篇关于如何从文件中读取Java中的double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆