简体   繁体   English

将文件中的双打相加

[英]Summing the doubles from a file

I've got a.txt file and here's its content:我有一个 .txt 文件,这是它的内容:

1.1, 1.2, 1.3, 2.0, 1.8 1.1、1.2、1.3、2.0、1.8

1.3, aa, 4.5, 6.7, 2.1 1.3、AA、4.5、6.7、2.1

3.5, 7.7, 9.9, 4.1, 2.1 3.5、7.7、9.9、4.1、2.1

I've got to load all lines from it, and if there'a double, sum it and show at the end.我必须从中加载所有行,如果有双行,请将其相加并显示在最后。

I've written this program:我写了这个程序:

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


public class Main3 {

    public static void main(String[] args) {

        File main3File = new File("Main3.txt");
        double sum = 0;

        try {
            Scanner scan = new Scanner(main3File);
            scan.useDelimiter(", ");
            while (scan.hasNextLine()) {
                if (scan.hasNextDouble()) {
                    sum += scan.nextDouble();
                    System.out.println(sum);
                }
            }
        } catch (FileNotFoundException ex) {
            System.out.println("Blad");
        }

        System.out.println("Suma: " + sum);
    }
}

Here's the output:这是 output:

1.1
2.3
3.5999999999996
5.6

So it sum the first three numbers, then stop and the while loop doesn't stop (if I write something under 'if', it shows without stopping).所以它将前三个数字相加,然后停止并且while循环不会停止(如果我在'if'下写了一些东西,它会显示而不会停止)。 It doesn't sum the last number (1.8) and it doesn't go to the next line.它不会将最后一个数字 (1.8) 相加,也不会将 go 加到下一行。

I guess it's something wrong with delimeter, right?我猜是定界符有问题,对吧? But I don't have idea how to change it.但我不知道如何改变它。 Do you have an idea?你有想法吗?

The main problem is you are mixing up lines and numbers, it may be better to process them separately.主要问题是您混淆了行和数字,最好单独处理它们。

If you process the lines and numbers separately, it's easier to be sure your loop condition is correct:如果您分别处理行和数字,则更容易确保您的循环条件正确:

Scanner lineScanner = new Scanner(file);
// Loop through lines
while (lineScanner.hasNextLine()) {
    String line = scan.nextLine();
    Scanner numberScanner = new Scanner(line);
    numberScanner.useDelimiter(", ");
    // Loop through numbers in each line
    while (numberScanner.hasNextFloat()) {
        float value = numberScanner.nextFloat();
        // do something with each value
    }
    System.out.println(sum);
}

If you really need to process the file in a single loop, then you need to use a delimiter that caters for the comma and any whitespace:如果您确实需要在单个循环中处理文件,那么您需要使用适合逗号和任何空格的分隔符:

Scanner scan = new Scanner(main3File);
scan.useDelimiter("\\s*,\\s*");
while (scan.hasNext()) {
    String next = scan.next();
    try {
        float value = Float.valueOf(next);
        // do something with each value
    } catch (NumberFormatException e) {
        // not a float
    }
}

\\s* is a pattern meaning 0 or more repetitions of any whitespace character. \\s*是一种模式,表示任何空白字符的 0 次或多次重复。

Read one line at a time and split with comma to get the values.一次读取一行并用逗号分隔以获取值。 Check further if value is a double or not.进一步检查 value 是否为 double。

        File main3File = new File("Main3.txt");
        double sum = 0;

        try {
            Scanner scan = new Scanner(main3File);
            String line ;
            while (scan.hasNextLine()) {
                line = scan.nextLine();
                String[] values = line.trim().split("\\s*,\\s*");
                for (String value : values) {
                    try {
                        double num = Double.parseDouble(value);
                        sum = sum + num;
                        System.out.println(sum);
                    } catch (NumberFormatException e) {
                        // System.out.println("Value is not double. hence ignored");
                    }
                }
            }
        } catch (FileNotFoundException ex) {
            System.out.println("Blad");
        }
        System.out.println("Suma: " + sum);

Let me know if you have any doubts !如果您有任何疑问,请告诉我!

1 ) Your code has a algorithm problem. 1)您的代码有算法问题。

//There is a infinite loop below. You are checking next scan and handling it if it's double
//But you keep continue to loop without passing next if it is not double, this causes infinite loop
while (scan.hasNextLine()) {
            if (scan.hasNextDouble()) {
                sum += scan.nextDouble();
                System.out.println(sum);
            }
        }

You have to add else statement and pass next like stated blow;您必须添加 else 语句并像声明的打击一样通过下一个;

else{
     scan.next();
}  

2 ) You can not delimit line using 2)你不能使用划线

numberScanner.useDelimiter(", ");

Because you have got a multi-lined text, which scanner sees your text's end of line as a special character ("\n").因为您有一个多行文本,扫描仪将您的文本的行尾视为特殊字符(“\n”)。 Yoo better use another way to parse, may be splitting it with String's .split method. Yoo 最好使用另一种解析方式,可能是用 String 的.split方法拆分它。

Hope it helps.希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM