英文:
How to sum numbers that are in columns from a text file in Java?
问题
我正在尝试从一个包含多行的文件中读取内容,然后将列中的数字相加。然而,我在将同一行中的数字分离为整数变量方面遇到了困难,以便最终可以将它们相加。
基本上,我想知道如何从文件中读取内容并对下面的列求和:
11 33
22 2
33 1
这样我将会得到 66 和 36。
英文:
I am trying to read from a file with multiple lines and then add the numbers in columns. However, I struggle to separate numbers into int variables from same lines so that I could add them eventually.
Basically, I would like to know how to read from a file and sum the columns below:
11 33
22 2
33 1
So that I would get 66 and 36
答案1
得分: 0
假设文件名为"filename.txt"...
import java.io.BufferedReader;
import java.io.FileReader;
public class SumColumns
{
public static void main(String args[])
{
int firstCol = 0, secondCol = 0;
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("./filename.txt"));
String line;
String[] columns;
while ((line = reader.readLine()) != null) {
columns = line.split(" ");
firstCol += Integer.parseInt(columns[0]);
secondCol += Integer.parseInt(columns[1]);
}
} catch (Exception e) {
}
System.out.println(firstCol);
System.out.println(secondCol);
}
}
英文:
Assuming the file name is "filename.txt"...
import java.io.BufferedReader;
import java.io.FileReader;
public class SumColumns
{
public static void main(String args[])
{
int firstCol = 0, secondCol = 0;
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("./filename.txt"));
String line;
String[] columns;
while ((line = reader.readLine()) != null) {
columns = line.split(" ");
firstCol += Integer.parseInt(columns[0]);
secondCol += Integer.parseInt(columns[1]);
}
} catch (Exception e) {
}
System.out.println(firstCol);
System.out.println(secondCol);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论