If I have a .txt file with a list of numbers. It should return the sum for all the numbers in each line as well as the sum of every number in the file. Then print all of this in the console. Lets say the txt file is:
50 3 21 10 9 9 54 47 24 74
22 63 63 28 36 47 60 3 45 83
20 37 11 41 47 89 9 98 40 94
48 77 93 68 8 19 81 67 80 64
41 73 24 29 99 6 41 23 23 44
43 41 29 11 43 94 62 27 81 71
83 14 97 67 21 68 77 25 21 24
31 8 54 14 49 96 33 18 14 80
54 55 53 38 62 53 62 10 42 29
17 89 92 87 15 42 50 85 68 43
This is my code:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Summer {
public static void main(String args[]) throws IOException {
File text = new File("src/nums.txt");
if (!text.exists()) {
text.createNewFile();
}
int sum = 0;
Scanner input = new Scanner(text);
while (input.hasNextInt()) {
sum = sum + input.nextInt();
}
System.out.printf("Sum of all numbers: %d", sum);
int lineSum = 0;
int lineNum = 1;
while (input.hasNext()) {
if (input.hasNextInt()) {
lineSum = lineSum + input.nextInt();
} else {
input.next();
lineNum++;
}
}
System.out.printf("%nSum of line %d: %d", lineNum, lineSum);
}
}
Which outputs:
Sum of all numbers: 4687
Sum of line 1: 0