Results 1 to 3 of 3
  1. #1
    Landon is offline Member
    Join Date
    Sep 2010
    Posts
    5
    Rep Power
    0

    Default Loop cancelling at end of line?

    hi, I'm trying to read in a .txt file which is working fine. I've also built the loops to determine if the next token is a number or word. The problem I'm having though is that when my loop hits the end of the line it prints the students total instead of going to the next line and collecting more data. As you'll be able to see the program should print out
    Student Name
    score score score .... Total:
    and so on....

    however it will print
    Student name
    score score Total:
    score
    score
    score

    the students scores can be stored on multiple lines
    the .txt file i'm reading in looks something like this

    bob 54 34 23 56
    45 45 23 45
    45 fred 23
    23 54
    34
    34
    and so on...

    any hints on how to continue the loop to the next line without printing the students totals? and where to put it? Thanks

    Java Code:
    import java.io.*;
    //For String tokenizer
    import java.util.*;
     
    public class Assignment1
    {
        public static void main(String[] args)
        {
            //Prompt user for filename
            System.out.println("Please type file name and press Enter: ");
            //Create kbd as a new BufferedReader
            BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));
            //Set filename to null
            String filename = null;
            
            //Read kbd into the String filename
            try 
            {
             filename = kbd.readLine();
            } 
            
            //Catch IO Exception and exit
            catch (IOException e) 
            {
             System.out.println("Filename was not correct.");
             System.exit(0);
            }
            
            //Create new file
            File file = new File("filename");
            //Create String buffer for the .txt file
            StringBuffer contents = new StringBuffer();
            //Create new BufferedReader named reader and set to null
            BufferedReader reader = null;
     
            //Enter the filename into reader
            try
            {
                reader = new BufferedReader(new FileReader(filename));
                //Set new String text to null
                String text = null;
     
                // Loop repeats until file is empty
                while ((text = reader.readLine()) != null)
                {
                    contents.append(text).append(System.getProperty("line.separator"));
                }
            } 
            
            //Catch Exception if file is not found or something goes wrong and terminate
            catch (FileNotFoundException e)
            {
                System.out.println("The filename entered was not found, program will now terminate.");
            } 
            
            catch (IOException e)
            {
                System.out.println("The filename entered was not found, program will now terminate.");
            } 
            
            finally
            {
                try
                {
                    if (reader != null)
                    {
                        reader.close();
                    }
                } 
                
                catch (IOException e)
                {
                    System.out.println("The filename entered was not found, program will now terminate.");
                }
                
            }
            
        //Create new String newStr contains the contents of the String buffer
        String newStr = contents.toString();
        
        //Create new String Tokenizer named StrTok
        //Create new string tokenizer StrTok
        StringTokenizer StrTok = new StringTokenizer(newStr, " ");
        //New string
        String token;
        //    Set State to 1
        int State = 1;
        
        //Declare number variable
        int number=0;
        int totalscore=0;
        int filetotal=0;
        
        String fullname = "";
        
        //Set Loop to run while there are more tokens
        while(StrTok.hasMoreTokens())
        {
            //Make new String for tokens
            String S = StrTok.nextToken();
                            
            //Loop for first state
            if (State == 1)
            {                        
                if(isNumber(S) == false)
                {
                    fullname = S;
                    State = 2;
                }
                continue;
            }
            if (State == 2)
            {
                if(isNumber(S) == true)
                {
                    //When encountering first number print out the name
                    System.out.println(fullname);
                    //Empty fullname for next student
                    fullname="";
                    
                    //Set token to equal number
                    number = Integer.parseInt(S);
                    System.out.print(number+" ");
                    
                    //Calculate totalscore
                    totalscore = totalscore + number;
                
                    //Advance to next state
                    State = 3;
                }
                
                //Else means next token is a word
                else
                {
                    //Add newest name to fullname
                    fullname = fullname + " "+S;
                    //Stay in name part of loop
                    State = 2;
                }
                continue;
            }
            if (State == 3)
            {
                //If next token = number
                if(isNumber(S) == true)
                {
                    //Set new token to number
                    number=Integer.parseInt(S);
                    //Add score to total
                    System.out.print(number+" ");
                    totalscore = totalscore + number;
                    //Stay in number loop
                    State = 3;
                }
                
                else
                {
                    if(!S.equals("total"))
                    {
                        System.out.println("total "+totalscore);
                        State=2;
                        fullname=S;
                        totalscore=0;
                    }
                    else
                        State = 4;
                }
                continue;
            }
                
            //State 4
            if(State == 4)
            {
                //Check if token after total is number
                if(isNumber(S) == true)
                {
                    //If token after total is a number that number must be
                    //the students total, check to see if the total from the
                    //file equals the total the program added up
                    filetotal = Integer.parseInt(S);
                    if(filetotal == totalscore)
                    {
                        System.out.println("total "+filetotal);
                        //Reset variables for next student and go back to loop start
                        number = 0;
                        totalscore = 0;
                        filetotal = 0;
                        State = 1;        
                    }
                    //if totals do NOT match print out total from file w/ an *
                    else
                    { 
                        System.out.println("total "+filetotal + "*");
                        //Reset variables for next student and go back to loop start
                        number = 0;
                        totalscore = 0;
                        filetotal = 0;
                        State = 1;                        
                    }
                }
                //if next token is not a number, total must be part of a name
                else
                {
                    //Print total score
                    System.out.println("total " + S);
                
                    //Reset Variables
                    number = 0;
                    totalscore = 0;
                    filetotal = 0;
                    fullname = "";
                        
                    //keep total because it is part of the name and 
                    //go back to state 2
                    State = 2;
                }
                continue;
            }
            
            //State 5
            if (State == 5)
            {
                //means we have hit the beginning of a new name
                //print out the total for previous student
                System.out.println(totalscore);
                
                //Reset variable for the next student
                number = 0;
                totalscore = 0;
                filetotal = 0;
    
                fullname = "";
                    
                //Keep previous token as the beginning of the new name
                fullname = fullname + S;
                
                //Goto State 2
                State = 2;
            }
        //Closes while loop
        }                                        
    }                                
        public static boolean isNumber(String S)
        {
            //Loop to determine if next token is a number of word
            //if loop returns true, token is a number
            //if loop returns false, token is a word
            for (int i = 0; i < S.length(); i++)
            { 
                 if (Character.isDigit(S.charAt(i)) == false)
                          return false;
            }
    
            return true;
        }
    
    
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Your main method is over 200 lines long and has a ton of redundancy. Before you go any further, you should do yourself (and us!) a favor and refactor the code. If you break it up into just a few appropriate methods will eliminate a lot of repetition and make your code much more understandable to you and to us and will make debugging much simpler.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Other suggestions:

    I would read in and analyze everything from the get-go rather than using a StringBuffer or StringBuilder. You know that the java.util.Scanner has several methods that can help you including hasNext(), hasNextInt(), next(), and nextInt(). With these methods, you could get rid of your difficult to decipher "state" ints. In fact a reasonable pseudocode loop could look something like:

    Java Code:
    while scanner has next token
      get the scanner's next token and place it into a name String variable
      while scanner has next int
         use scanner to read in next int, add to total, and increment a counter
      end while scanner has next int 
      use the total and counter to figure out average
      use this and the name to display results
      clear the above variables
    end while scanner has next token

Similar Threads

  1. Replies: 2
    Last Post: 07-02-2010, 03:20 PM
  2. simple line problem / for loop problem
    By helpisontheway in forum New To Java
    Replies: 1
    Last Post: 11-17-2009, 07:12 AM
  3. Query regarding cancelling long run jobs
    By joydev in forum Threads and Synchronization
    Replies: 3
    Last Post: 07-03-2009, 05:19 AM
  4. Replies: 3
    Last Post: 02-16-2009, 10:20 PM
  5. how to print output on same line in 'while loop'?
    By acidblue in forum New To Java
    Replies: 5
    Last Post: 12-13-2007, 03:30 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •