从Java中的文件中读取数字数据

时间:2016-06-23 10:26:11

标签: java string file double delimiter

我必须添加文件的数字内容。 棘手的部分是数字内容也可以附加。

例如,短语abc123,123abc或abc123def应被视为123.此外,abc123.4或123.4abc或abc123.4abc应被视为123.4如果数字多于点数,则不应该被视为有效数字,应予以忽略。

1 个答案:

答案 0 :(得分:1)

试试这个,用注释替换使用你自己的文件而不是字符串

    // Use this instead when you want to try with your own file
    // String source = new String(Files.readAllBytes(Paths.get(filePath)));

    String source = "23 , 23.2 asf 2asfd 2.3asf";
    source = source.replaceAll("[^0-9\\.]+", " ");

    double accumulator = 0;

    try (Scanner doubleScanner = new Scanner(source)) {
        doubleScanner.useLocale(Locale.US);
        while (doubleScanner.hasNextDouble()) {
            double num = doubleScanner.nextDouble();
            System.out.println("Found :" + num);
            accumulator += num;
        }
    }
    System.out.println("Sum :" + accumulator);

打印

Found :23.0
Found :23.2
Found :2.0
Found :2.3
Sum :50.5