Results 1 to 11 of 11
  1. #1
    RSYR is offline Member
    Join Date
    Nov 2009
    Posts
    9
    Rep Power
    0

    Exclamation Scanner, while loop and sorting arrays/string?

    I have been given a homework assignment and left it till the last minute :(
    I'm required to scan in a text file in the following format:

    Leeds United : Liverpool : 1 : 2
    Chelsea : Manchester City : 1 : 1
    Aston Villa : Middlesbrough : 3 : 1
    Tottenham Hotspur : Stoke City : 0 : 0

    But with alot more entries. I first need to split these at each colon.
    Then i need to arrange the result so it outputs as the following:

    Leeds United 1 Liverpool 2
    Chelsea 1 Manchester United 1
    Aston Villa 3 Middlesbrough 1
    Tottenham Hotspur 0 Stoke City 0

    The code i have so far keeps throwing this:

    Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)

    The code is:
    Java Code:
    	import java.io.File;
    	import java.io.FileNotFoundException;
    	import java.util.Scanner;
    
    	public class anotherreader {
    
    	    public static void main(String[] args) throws FileNotFoundException {
    	    	
    	        File file = new File("results2.txt"); // Location of file to read
    	        
    
    	            Scanner s = 
    	            new Scanner(file).useDelimiter("\\s*:\\s*"); // Split each line at each colon
    	
    
    	            String homet = s.next(); //assign home team name
    	            String awayt = s.next(); //assign away team name
    	            int homes = s.nextInt(); //assign home team score
    	            int aways = s.nextInt(); //assign away team score
    	            
    	            System.out.print(homet); //print home team name to screen
    	            System.out.print(homes); //print home team score to screen
    	            System.out.print(awayt); //print away team name to screen
    	            System.out.println(aways); //print away team score to screen
    
    	            s.close();
                    
    	        }
    	        
    	    }
    I'm guessing i need to sort out the scanner so it stops giving me the error.
    After this i'm going to need some sort of while loop to keep repeating the scanning for each line of text i presume?
    And finally i need to validate the results as there cannot be a missing score or team name.

    Sorry this is so long i've only just started with java and this is my first assignment which i obviously can't do :(

    Any help/tips/suggestions would be greatly appreciated. Thanks

  2. #2
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    You might be better off creating an Object that stores the homet/homes/awayt/aways information and using setter methods to populate the fields. You can store those objects in an array for easy access.
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  3. #3
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    Chelsea 1 Manchester United 1? Throw away that file.

    Just read line by line. Split each line into an array by colon, line.split(":"), and swap the second and third elements.

  4. #4
    RSYR is offline Member
    Join Date
    Nov 2009
    Posts
    9
    Rep Power
    0

    Default

    Hi thanks for the quick replies.
    I've split the file before using this code:
    Java Code:
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.IOException;
    
    public class linebased {
        public static void main(String[] args) throws IOException {
            BufferedReader inputStream = null;
    
            try {
                inputStream = new BufferedReader(new FileReader("results2.txt"));
     
                String text;
                while ((text = inputStream.readLine()) != null) {
                	
                	String [] splitupText = text.split(":");// split the text into multiple elements
                	
        			for ( int i = 0; i < splitupText.length; i++ ) {	// loop over each element
      
        				String nextBit = splitupText[i];				// get the next element (indexed by i)
        				
        				nextBit = nextBit.trim();						// use the trim method to remove leading and trailing spaces
        				 				
        				System.out.println(nextBit);					// display the next element	
        				
        			}
        			
                }
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
            }
        }
    }
    I'm not exactly sure how i would go about swapping the second and third elements...
    Also... after this i have to create something that will count the number of valid games, invalid games and total goals scored... so would probably need a parse for this?
    Sorry i'm not trying to be a pain but i've never really used Java before

  5. #5
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    If you want to print out the elements of the array just to see what's there just use

    Java Code:
    java.util.Arrays.toString(splitupText );
    For the swapping let's see your attempt. You could just use a temp String variable ...

  6. #6
    RSYR is offline Member
    Join Date
    Nov 2009
    Posts
    9
    Rep Power
    0

    Default

    okay for the swapping what i tried was:

    Java Code:
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.IOException;
    
    public class linebased {
        public static void main(String[] args) throws IOException {
            BufferedReader inputStream = null;
    
            try {
                inputStream = new BufferedReader(new FileReader("results2.txt"));
     
                String text;
                while ((text = inputStream.readLine()) != null) {
                	
                	String [] splitupText = text.split(":");// split the text into multiple elements
                	
        			for ( int i = 0; i < splitupText.length; i++ ) {	// loop over each element
      
        				//String nextBit = splitupText[i];				// get the next element (indexed by i)
        				
        				//nextBit = nextBit.trim();						// use the trim method to remove leading and trailing spaces
        				 				
        				//System.out.println(nextBit);					// display the next element	
        				System.out.print(splitupText[0]);
        				System.out.print(splitupText[2]);
        				System.out.print(splitupText[1]);
        				System.out.println(splitupText[3]);
        			}
        			
                }
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
            }
        }
    }
    This gives me the desired order of the string but i get the string repeated another 3 times.

  7. #7
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    You didn't swap the values inside the array at all? You just printed them in a different order. Where is the String temp variable that I talked about above?

  8. #8
    RSYR is offline Member
    Join Date
    Nov 2009
    Posts
    9
    Rep Power
    0

    Default

    i don't understand how to do that at all to be honest. I've just had a try at implementing various different things i got in the search when looking for "temporary variables" and also searching for "java.util.Arrays.toString(splitupText );".

    However after playing with the code i did manage to get the order i wanted..

    Leeds United 1 Liverpool 2
    Chelsea 1 Manchester City 1
    Aston Villa 3 Middlesbrough 1
    Tottenham Hotspur 0 Stoke City 0

    but now i need to find a way of sorting out which results were valid and which were not. And also counting the number of valid results, invalid results and total goals scored. Any ideas? thanks

    EDIT:
    Sorry just to mention i managed to get the order using the following:

    System.out.print(splitupText[0]); // prints the home team name to screen
    System.out.print(splitupText[2]); // prints the home team score to screen
    System.out.print(splitupText[1]); // prints the away team name to screen
    System.out.println(splitupText[3]); // prints the away team score to screen

    I just needed to move the printing out of the loop. Which now i think about it was quite obvious.
    Last edited by RSYR; 11-04-2009 at 09:52 PM. Reason: Addition to post

  9. #9
    wnaksniff is offline Member
    Join Date
    Nov 2010
    Posts
    1
    Rep Power
    0

    Default

    any more help on this

  10. #10
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,041
    Rep Power
    10

    Default

    Quote Originally Posted by wnaksniff View Post
    any more help on this
    This thread has been dead for a year. If you have a similar question, feel free to start your own thread and link to this one.

  11. #11
    kittykat850 is offline Member
    Join Date
    Apr 2011
    Posts
    8
    Rep Power
    0

    Default

    EDIT:
    Sorry just to mention i managed to get the order using the following:

    System.out.print(splitupText[0]); // prints the home team name to screen
    System.out.print(splitupText[2]); // prints the home team score to screen
    System.out.print(splitupText[1]); // prints the away team name to screen
    System.out.println(splitupText[3]); // prints the away team score to screen

    I just needed to move the printing out of the loop. Which now i think about it was quite obvious.[/QUOTE]

    How do I move it out of the loop?

Similar Threads

  1. while loop bypasses scanner input on 2nd pass
    By xf021209 in forum New To Java
    Replies: 2
    Last Post: 02-28-2010, 09:10 AM
  2. Problem with scanner in loop
    By grifan526 in forum New To Java
    Replies: 2
    Last Post: 07-21-2009, 01:06 AM
  3. Scanner-While Loop
    By hyunski in forum New To Java
    Replies: 2
    Last Post: 03-12-2009, 03:15 AM
  4. String tokenizing with Scanner
    By vijaygk in forum Advanced Java
    Replies: 2
    Last Post: 07-15-2008, 05:44 AM
  5. Replies: 0
    Last Post: 11-20-2007, 05:59 PM

Posting Permissions

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