Java 对文件中的双精度进行求和
我有一个.txt文件,下面是它的内容: 1.1,1.2,1.3,2.0,1.8 1.3、aa、4.5、6.7、2.1 3.5,7.7,9.9,4.1,2.1 我必须从中加载所有行,如果有双精度,求和并在末尾显示 我写了这个程序:Java 对文件中的双精度进行求和,java,Java,我有一个.txt文件,下面是它的内容: 1.1,1.2,1.3,2.0,1.8 1.3、aa、4.5、6.7、2.1 3.5,7.7,9.9,4.1,2.1 我必须从中加载所有行,如果有双精度,求和并在末尾显示 我写了这个程序: import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Main3 { public static void mai
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);
}
}
以下是输出:
1.1
2.3
3.5999999999996
5.6
因此,它将前三个数字相加,然后停止,而while循环不会停止(如果我在“if”下写入内容,它将不停止显示)。它不求最后一个数字(1.8)的和,也不转到下一行
我猜是delimeter出了问题,对吧?但我不知道如何改变它。你有什么想法吗?主要问题是你把行和数弄混了,最好是分开处理 如果单独处理行和数字,则更容易确保循环条件正确:
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);
}
如果确实需要在单个循环中处理文件,则需要使用符合逗号和任何空格的分隔符:
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*
是一种模式,表示任何空格字符重复0次或多次。一次读取一行,并用逗号分隔以获取值。进一步检查值是否为双精度
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);
如果您有任何疑问,请告诉我 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);
}
}
您必须添加else语句,然后像所述的打击一样通过下一步
else{
scan.next();
}
2)您不能使用
numberScanner.useDelimiter(", ");
因为您有一个多行文本,扫描仪会将文本的行尾视为一个特殊字符(“\n”)。Yoo最好使用另一种解析方法,可能是使用String的.split方法对其进行拆分
希望能有所帮助。我建议您使用
do while
do{//对项目做点什么……}while(a>b)代码>