DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Threaded View

  1. #1
    Join Date
    Sep 2003
    Posts
    1

    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;
    }
    }
    Attached Files

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


Top DevX Stories

Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL


Sponsored Links