javaLearner javaLearner - 1 month ago 4
Java Question

How to add string token numbers from a text file in Java

The text file(myfile.txt) has the numbers as follows:

6
19
20
23
34
45
47
51
54
56
61
70
72
76
90
93
94
96
105
111


I can read and print this text file in Java as a string token and my code is:

File fileName = new File("myfile.txt");
Scanner inFile = new Scanner(fileName);
while (inFile.hasNext())
{
token = inFile.next( );

System.out.println(token);

}

inFile.close();


Now how can I get the sum of these numbers in java? I mean SUM(6+19+20+23+..........+111)

Answer

use an int variable sum , and use scanner.nextInt() to extract the number. and do the addition on every iteration.

                      File fileName = new File("myfile.txt");         
                      Scanner inFile = new Scanner(fileName);
                       int sum=0;        
                      while (inFile.hasNext())         
                      {         
                           sum+= inFile.nextInt( );     
                      } 
                      System.out.println(sum);

                    inFile.close();