Search code examples
javafileinputstreamdatainputstream

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


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 !


Solution

  • 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