Program to add two integer numbers read from a text file and displaying results on console [closed]

StackOverflow https://stackoverflow.com/questions/16318749

Even after lots of trial and error, I am unable to figure out how to write a java program that adds 2 integers (read from a text file) and displays addition result on the console.

I tried using FileInputStream, DataInputStream classes ...

Example explaining what I exactly need !

Suppose there are 2 integers stored in a text file (sample.txt) .... Let 1 and 2 be the integers.

I would like to read those integers from the file and display their sum (= 3) on the console

Any help would be appreciated !

P.S: I am a beginner in Java, so please be as simple as you can wrt coding !

有帮助吗?

解决方案

Here's something you could start with:

import java.util.Scanner;
import java.io.*;

public class MyClass {

    public static void main(String[] args) throws IOException {

        Scanner s = new Scanner(new File("sample.txt"));
        int tmp1 = s.nextInt();
        int tmp2 = s.nextInt();
        System.out.println(tmp1 + tmp2);
    }
}

Create the text file directly under the Project root in Eclipse.

Sample content can be:

1 2

其他提示

Your question isn't very clear at all, but providing you have the ints stored in a text file i.e

//sample.txt
1 2

You can use a Scanner to read the text file into an array of ints

Scanner scanner = new Scanner(new File("sample.txt"));

int [] numbers = new int [5];
int i = 0;
while(scanner.hasNextInt()){
   numbers[i++] = scanner.nextInt();
}

then print the result

int sum = 0;
for (int i = 0; i < numbers.size(); i++)
    sum += numbers[i];
System.out.println(sum);

(This will work for a text file of numbers up to 5 long) change "new int [5];" to have the number of elements you want as desired i.e new int [2];)

Hopefully this will be useful

Try this:

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader("try.txt"));
    String line ="";
    int sum =0;
    while((line = br.readLine())!= null)
        sum = sum + Integer.parseInt(line);
    System.out.println(sum);
}

File try.txt:

1
2

Output:

3
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top