【发布时间】:2017-06-10 06:26:55
【问题描述】:
如何从文本文件中获取数据并将其保存到字符串中?
例如,我的文本文件有数字 1、4、5、6、8 和 10.4。这些数字可以在同一行,也可以在不同的行。我想将它们连接成一个字符串,如下所示:1 4 5 6 8 10.4
import java.io.File;
import java.io.FileNotFoundException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;
public class f {
public static void main(String args[]) {
int count = 0;
double totalcount = 0;
double average = 0;
Scanner read = new Scanner(System.in);
Scanner file;
String input = "";
String test = "";
double[] array1 = new double[100];
while (true) {
System.out.println("Enter name of file or enter quit to exit");
input = read.next();
if (input.equalsIgnoreCase("quit")) {
break;
}
try {
file = new Scanner(new File(input));
if (!file.hasNextLine()) {
System.out.println(input + " file is empty");
}
while (file.hasNext()) {
totalcount = totalcount + file.nextDouble();
count++;
}
while (file.hasNext()) {
test = test + (" ") + file.next();
}
System.out.println("bla" + test);
average = totalcount / count;
DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.CEILING);
System.out.println("\nCount: " + count);
System.out.println("Total: " + df.format(totalcount));
System.out.println("Average: " + df.format(average));
System.out.println();
} catch (FileNotFoundException e) {
System.out.println(input + " doesn't exist");
}
}
}
}
我的代码不能正常工作。
【问题讨论】:
-
听起来不错。到目前为止,此请求有任何错误吗?
-
嗯,这就是我目前所拥有的,但它不起作用。 while (file.hasNext()) { test = test + (" ") + file.next(); }
-
您能否在问题本身中显示minimal reproducible example?请edit
-
我刚刚发布了到目前为止的内容,有点乱,我的目标是从用户那里获取文件名,然后将文件的内容保存到字符串中然后进行处理。
-
你在第一个
while (file.hasNext()) {之后用尽了整个扫描仪