简体   繁体   English

如何在文件的同一行中添加两个数字

[英]How to add two numbers in the same row of a file

Hello I need to add two integers in the same row of a file, separated by tab. 您好,我需要在文件的同一行中添加两个整数,以制表符分隔。

My file abc.txt has the following entry: 我的文件abc.txt具有以下条目:

12  123
15  456

My program needs to add 12 with 123 and 15 with 456. 我的程序需要将123加12,并将456加15。

I am able to split the two entries in a row and convert them to integer, but I don't know how to treat them as separate numbers and add them. 我能够将两个条目连续拆分并转换为整数,但是我不知道如何将它们视为单独的数字并将其相加。

For example, if I try to add then 12 adds with 12 and 123 adds with 123, where it should be 12+123. 例如,如果我尝试添加,则12与12相加,而123与123相加,其中应为12 + 123。

Here is my program: 这是我的程序:

import java.io.*;
public class test {

    public static void main(String[] args) {
        String s = "";
        FileInputStream finp = null;
        InputStreamReader inpr = null;
        BufferedReader br = null; 

        try {
            finp = new FileInputStream(args[0]);
            inpr = new InputStreamReader(finp);
            br = new BufferedReader(inpr);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            while (true) {
                s = br.readLine();
                if (s == null)
                    break;

                for (int i = 0; i < 2; i++) {
                    String [] addrs = s.split("\t");
                    int a = Integer.parseInt(addrs[i]);
                    System.out.println(a + a);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Bring your addrs variable out of the for loop, it is currently getting overwritten every iteration and you don't want that. 将您的addrs变量带出for循环,当前每次迭代都会覆盖它,而您不希望这样。

If your file will always have two numbers per row, you don't need a for-loop, you can just add them by using their indices: 如果文件每行始终有两个数字,则不需要for循环,只需使用它们的索引将它们添加即可:

String [] addrs = s.split("\t");
int a = Integer.parseInt(addrs[0]);
int b = Integer.parseInt(addrs[1]);
System.out.println(a + b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM