Help! I need to write a program that reads a text file with numbers and sums up each line of numbers. Then write a part of the program that outputs the text to another file. How do I do this?
Here's what the data file looks like:
1 2
2 3
3 4
4 5
5 6
Here is the code I have:
-
import java.util.Scanner;
-
import java.io.File;
-
import java.io.PrintWriter;
-
-
public class SumFile
-
{
-
public static void main( String[] args ) throws Exception
-
{
-
-
File f = new File("data.txt");
-
-
Scanner input = new Scanner(f);
-
-
String name;
-
int number;
-
int sum;
-
-
-
while ( input.hasNext() )
-
{
-
number = input.nextInt();
-
number = input.nextInt();
-
number = input.nextInt();
-
number = input.nextInt();
-
number = input.nextInt();
-
number = input.nextInt();
-
-
sum= number + number;
-
-
System.out.printf("The file sum is " + sum);
-
}
-
File g = new File("result.txt");
-
-
PrintWriter output = new PrintWriter(g);
-
output.println
-
-
-
input;.close();
-
}
-
}
-
You can just use Formatter for writing file....(Useful for debugging)
And Scanner for reading...
Your implementation is confusing....
When you read the data inside the file, you must store them in different variable...
You are just simply storing the values in a variable only...
For example,
1 2
2 3
3 4 -> the node is on this now....Assuming....
The number variable gets the 4 (last value before EOF)
And you are just summing the same value 4 + 4 = 8
You cannot say 3 + 4 = 7 Base on your code posted....
Maybe like this:
- datatype sum set zero
-
-
while( StillHasValueAtNextPointing ) {
-
num1 = firstvalueCurrentLine
-
num2 = secondValueCurrentLine
-
sum += ( num1 + num2 )
-
}
-
-
Save the sum into another file....
Correct me if im wrong,
Sukatoa