-
Notifications
You must be signed in to change notification settings - Fork 3
/
Sum_ofintegers.java
42 lines (41 loc) · 1.16 KB
/
Sum_ofintegers.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.io.*;
public class Sum_ofintegers
{
public static void main(String args[])
{
try
{
FileReader fr = new FileReader("integers.txt");
FileWriter fw = new FileWriter("sum.txt");
int digit = fr.read();
int sum=0;
int total_sum =0;
while(digit!= -1)
{
if(digit == (int)' ')
{
//completed number
fw.write(sum +" ");
total_sum = total_sum+sum;
sum=0;
}
else
{
//single digit extracted
String s = String.valueOf((char)digit);
int single = Integer.parseInt(s);
sum = sum*10+single;
}
digit = fr.read();
}
fw.write("\n The sum of all numbers in the file is "+total_sum);
fw.close();
fr.close();
System.out.println("File operations complete");
}
catch(Exception e)
{
System.out.println(e);
}
}
}