如何在Java中对文本文件中列中的数字进行求和?

huangapple go评论64阅读模式
英文:

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);
	    
   }  
}

huangapple
  • 本文由 发表于 2020年10月8日 05:35:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64252641.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定