标题翻译
How do you calculate the sum of integer elements in an array using text files in Java?
问题
假设我有一个名为 "Scores.txt" 的文件,其中包含2个或更多个数组。
示例
10 20 30 40 50 //总和为150
11 21 31 41 51 //总和为155
我想要能够读取每行中的每个元素并将它们相加在一起。
另外还有跟进的问题。将整数数组正确地写入文本文件的方法是什么?如何分隔每个元素但仍然将它们放在同一行?
这是我用来编写数组的代码,但我觉得在读取元素时可能会有问题。
write() 代码
try {
File file = new File("Scores.txt");
BufferedWriter bWrite = new BufferedWriter(new FileWriter(file, true));
int score[] = new int[5];
System.out.println("输入分数: ");
for (int i = 0; i < 5; i++) {
score[i] = sc.nextInt();
}
for (int i = 0; i < 5; i++) {
bWrite.write(score[i] + " ");
}
bWrite.flush();
bWrite.close();
}
catch (Exception e) {
System.out.println("错误");
}
英文翻译
Lets say I have a "Scores.txt" file containing 2 or more arrays.
Example
10 20 30 40 50 //sum is 150
11 21 31 41 51 //sum is 155
I want to be able to read each elements in a line and add them up together.
Also follow up questions. What is the correct way to write an array of integers into a text file? How do you separate each elements but still place them in one line?
This is the code I'm using to write the arrays but I have a feeling that there might be issues when reading the elements.
write() code
try {
File file = new File ("Scores.txt");
BufferedWriter bWrite = new BufferedWriter(new FileWriter(file, true));
int score[] = new int [5];
System.out.println("Enter scores: ");
for (int i = 0; i < 5; i++) {
score[i] = sc.nextInt();
}
for (int i = 0; i < 5; i++) {
bWrite.write(score[i] + " ");
}
bWrite.flush();
bWrite.close();
}
catch (Exception e) {
System.out.println("ERROR");
}
专注分享java语言的经验与见解,让所有开发者获益!
评论