1 Attachment(s)
How do I get sum LINE BY LINE only????
Hi Everyone! I'm pretty new here and to java programming as well.
I was wondering if u guys could help me out. I got this program below... it compiles and runs.
The problem it adds all the numbers together and than returns the total value, what I would like it to do is get the sum of the numbers on each line only. So instead of getting one number (which is what I am getting) how do I get the sum of each line?
import java.io.*;
import java.util.*;
class FileTest
{
public static void main (String[] args)
{
Controller contr = new Controller();
System.out.println (contr.getSum());
}
}
class Controller
{
FileAccess fa = new FileAccess();
public int getSum()
{
int lineNum = 1;
int sum = 0;
String lineOfText;
fa.openFile("Kill.txt");
lineOfText = fa.readLine();
while (lineOfText != null)
{
System.out.println (lineNum);
StringTokenizer strToken = new StringTokenizer (lineOfText, ";");
while (strToken.hasMoreTokens())
{
sum += Integer.parseInt (strToken.nextToken());
}
lineNum++;
lineOfText = fa.readLine();
}
return sum;
}
}
class FileAccess
{
private BufferedReader br;
public void openFile (String fileName){
try
{
br = new BufferedReader (new FileReader (fileName));
}
catch (FileNotFoundException fnfe)
{
System.out.println ("File does not exist.");
}
}
public void closeFile()
{
try
{
br.close();
}
catch (IOException ioe)
{
System.out.println ("There was an input/output error");
}
}
public String readLine()
{
String lineOfText = null;
try
{
lineOfText = br.readLine();
}
catch (IOException ioe)
{
System.out.println ("There was an input/output error");
}
return lineOfText;
}
}