Page 1 of 2 12 LastLast
Results 1 to 20 of 27

Thread: Homework help

  1. #1
    rclausing is offline Member
    Join Date
    Oct 2009
    Location
    Oregon
    Posts
    22
    Rep Power
    0

    Default Homework help

    I'm a bit stuck on this, and it's the first time I am at a loss as to what direction to take. The problem: Write a program to process golf scores stored in a text file. Each line contains 5 values, par and the scores for 4 golfers. I need to determine a winner, and produce a table of the golfers scores.

    What I have so far:

    Java Code:
     import java.util.Scanner;
    import java.io.*;
    
    public class golfscores
    
    {
    	public static void main (String[] args) throws IOException
    	{
    		int g1score=0, g2score=0, g3score=0, g4score=0, par=0;
    		String scores;
    		Scanner fileScan, scoresScan;
    
    		fileScan = new Scanner (new File("scores.txt"));
    
    
    		while (fileScan.hasNext())
    		{
    
    			scores = fileScan.nextLine();
    			fileScan.useDelimiter(".");
    			System.out.println ("Par: " + fileScan.next());
    				System.out.println();
    
    			scoresScan = new Scanner (scores);
    			scoresScan.useDelimiter("/");
    
    			while (scoresScan.hasNext())
    				System.out.println("    " + scoresScan.next());
    
    			System.out.println();
    Obviously, this direction isn't working out.

    I know I need useDelimiter() to seperate each golfers scores, and then parseInt() the value to change it from a String to an Int so I can add each value to my variables g1score, g2score etc, but I am not sure how to go about that. Do I need 5 different deliminators, one for par and one for each individual golfer's scores?

    My table of data (text file without deliminators) looks something like:

    4 5 3 4 4
    5 8 4 5 5

    etc.

    Can anyone point me in the right direction? Do I need to use 5 nested while statements, and do a scan for each deliminator?

  2. #2
    collin389 is offline Senior Member
    Join Date
    Nov 2009
    Posts
    235
    Rep Power
    5

    Default

    Arrays might help store the information. I dont know why you would need 5 deliminators. Are you saying that the text file would look like this?
    4.5/3/4/4
    5.8/4/5/5
    Last edited by collin389; 11-23-2009 at 09:31 PM.

  3. #3
    rclausing is offline Member
    Join Date
    Oct 2009
    Location
    Oregon
    Posts
    22
    Rep Power
    0

    Default

    I don't know enough about arrays to take the text file and store it's info in an array. We only just started that chapter in our book, otherwise I probably would have tried to do it that way.

    And I do not know that I need 5 deliminators - I am just trying to figure out how to separate the data in the scores.txt file so that I can assign the individual values on each line to a variable. Then use a while loop to run through the whole file and add up each column of values.

    Java Code:
    while (fileScan.hasNext())
           add first # to Par
           add second # to g1score
           add thrid # to g2score
           add 4th # to g3score
           add 5th # to g4score
    go to next line
           add 1st # to current Par value
           add 2nd # to current g1score value
           etc, and doing this for each 18 lines of the .txt file
    something along those lines. I can't see any other way of doing this. which is why I need help!

  4. #4
    sky
    sky is offline Member
    Join Date
    Nov 2009
    Posts
    96
    Rep Power
    0

    Default

    Think about this:

    - Read one line of the file
    - Save the line into a String
    - Use the method split("<whatever delimiter you choose>")
    - At this point you have an array and each position contains one score.

  5. #5
    rclausing is offline Member
    Join Date
    Oct 2009
    Location
    Oregon
    Posts
    22
    Rep Power
    0

    Default

    OK, so I have
    Java Code:
    while (fileScan.hasNext())
    {
        scores = fileScan.nextLine(); //  save the Scanned line into a String
        String[] score = scores.split("/");  // use method String.split() 
    }
    Unfortunately, the String.split() method is not in our textbook. So I have had to look it up on the Sun Microsystems site. Not the most user friendly information. Can I then reference each position with an index # as you would in an array? i.e. g3score += score[3]

    As you can see, I am in the deep end and haven't yet quite figured out how to swim.

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

    Default

    Quote Originally Posted by rclausing View Post
    Unfortunately, the String.split() method is not in our textbook. So I have had to look it up on the Sun Microsystems site. Not the most user friendly information. Can I then reference each position with an index # as you would in an array? i.e. g3score += score[3]
    The beauty of programming is that you can try whatever you like here with little risk of breaking your computer. So my suggestion: try it! See if it works, and if it does, great! If not, come on back and we'll look at your new code.

    Best of luck!

  7. #7
    sky
    sky is offline Member
    Join Date
    Nov 2009
    Posts
    96
    Rep Power
    0

    Default

    I would like to add that Java API is difficult to read at the begining, but when you get use to it is very useful.

  8. #8
    collin389 is offline Senior Member
    Join Date
    Nov 2009
    Posts
    235
    Rep Power
    5

    Default

    So what does the text file look like with delimiters?

  9. #9
    rclausing is offline Member
    Join Date
    Oct 2009
    Location
    Oregon
    Posts
    22
    Rep Power
    0

    Default

    As I am sure you knew, it doesn't work. with that line g3score += score[3] I am trying to assign a string value to an Int variable - so I have to use parseInt(score) somehow to reassign the string value to an integer. I tried:
    Java Code:
    par = parseInt('score[0]'); // assign the first value of the first hole to par
    and got the error: unclosed character literal. I am not even sure what that means. It appears that I have the code correct insomuch as getting each line to store as a string array, so I guess I am on the right track. My brain is beginning to hurt though. Is there no way to give me a clue how to do this without giving away the whole problem?

  10. #10
    rclausing is offline Member
    Join Date
    Oct 2009
    Location
    Oregon
    Posts
    22
    Rep Power
    0

    Default

    Quote Originally Posted by collin389 View Post
    So what does the text file look like with delimiters?
    right now I just have 3 holes. I want the program to work right first, before I go in and assign values for par and the 4 golfer's scores to 18 holes:


    3/3/3/4/2
    4/3/4/4/4
    4/3/3/4/5

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

    Default

    Quote Originally Posted by rclausing View Post
    As I am sure you knew, it doesn't work.
    No one can assume this.

    I tried:
    Java Code:
    par = parseInt('score[0]'); // assign the first value of the first hole to par
    and got the error: unclosed character literal. I am not even sure what that means.
    It means that you probably should not have quotes around score[0].
    score[0] is a String so your placing char quotes around a String. Just try to parse it (right idea there!) without the single quotes.

    Is there no way to give me a clue how to do this without giving away the whole problem?
    You're heading in the right direction. Keep on plugging!

  12. #12
    collin389 is offline Senior Member
    Join Date
    Nov 2009
    Posts
    235
    Rep Power
    5

    Default

    So why did you say: fileScan.useDelimiter("."); if there are no periods in the text file?
    All you need to do is set the deliniter to "/" and then:
    while(file.hasNext())
    {
    s = readLine()
    par += s.nextInt()
    gscore1 += s.nextInt()
    gscore2 += s.nextInt()
    etc...
    }

    That was really fast, I don't know how you want to store everything but if you want all the score stored individually (not the sum), then use arrays.
    Last edited by collin389; 11-23-2009 at 11:47 PM.

  13. #13
    sky
    sky is offline Member
    Join Date
    Nov 2009
    Posts
    96
    Rep Power
    0

    Default

    I'm not sure about this, but I think that unless you import directly java.lang.Integer you should use Integer.parseInt() instead of only parseInt()

  14. #14
    rclausing is offline Member
    Join Date
    Oct 2009
    Location
    Oregon
    Posts
    22
    Rep Power
    0

    Default

    So I tried tackling this from another angle. I read ahead in the book to see if I could figure out how to do this with an array. here is what I have so far:

    Java Code:
    import java.util.Scanner;
    import java.io.*;
    
    public class golfscores1
    
    {
    	public static void main (String[] args) throws IOException
    	{
    		int g1score=0, g2score=0, g3score=0, g4score=0, par=0, counter=1;
    
    		Scanner fileScan, scoresScan;
    
    		fileScan = new Scanner (new File("scores.txt"));
    		while (counter <=18)
    		{
    			while (fileScan.hasNext())
    			{
    				int[] scores = new int[5];
    				for (int i=0; i<scores.length; i++)
    				{
    						scores[i]=fileScan.nextInt();
    
    				}
    					scores[0] += par;
    					scores[1] += g1score;
    					scores[2] += g2score;
    					scores[3] += g3score;
    					scores[4] += g4score;
    
    			}
    
    
    			//while (scoresScan.hasNext())
    			//	System.out.println("    " + scoresScan.next());
    
    			System.out.println();
    			counter ++;
    		}
    	}
    }
    This does not print out the table of scores (I will do that later) as I am just trying to get a handle on importing the values from the .txt file to the array. The code compiles, but I get a runtime error - Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:840)
    at java.util.Scanner.next(Scanner.java:1461)
    at java.util.Scanner.nextInt(Scanner.java:2091)
    at java.util.Scanner.nextInt(Scanner.java:2050)
    at golfscores1.main(golfscores1.java:38)

    my only guess is that it is looking for one primitive data type, and not getting it. I could not see where the error is. Did I try to cast a String object as an Integer somewhere?

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

    Default

    A rule for using Scanner: Each nextXXX must be preceded by a hasNextXXX of the same type. So you cannot do
    Java Code:
    while (fileScan.hasNext()) {
      int myInt = fileScan.nextInt();
    }
    but this is OK:
    Java Code:
    while (fileScan.hasNextInt()) {
      int myInt = fileScan.nextInt();
    }

    Also, you cannot do one hasNext and then follow this with a bunch of unchecked nextXXX in a for loop. So this fails on two accounts:
    Java Code:
          while (fileScan.hasNext()) { // one hasNext here
            int[] scores = new int[5];
            for (int i = 0; i < scores.length; i++) {
              scores[i] = fileScan.nextInt();  // a bunch of unchecked nextInts here
            }

    I'm not sure what your while (counter <= ...) loop is for, and you may wish to get rid of it. If it were me, I'd read in a line and split it and then simply print out the contents of the array returned to see what is going on. Then I could do more with the results. For instance, what if you simply try this:
    Java Code:
        while (fileScan.hasNextLine()) {
          // can do only one fileScan.nextLine() within this loop
          String line = fileScan.nextLine();
    
          String[] tokens = line.split("/");
    
          for (int i = 0; i < tokens.length; i++) {
            System.out.print(tokens[i] + "  ");
          }
          System.out.println();
        }
    Last edited by Fubarable; 11-24-2009 at 01:34 AM.

  16. #16
    rclausing is offline Member
    Join Date
    Oct 2009
    Location
    Oregon
    Posts
    22
    Rep Power
    0

    Default

    Fub -

    That is confusing to me. Your first two pieces of code look identical, so why would one work and the other not?

    The counting loop was to make sure the program would only instantiate 18 arrays, one for each hole.

    The for loop is to read the data from the .txt file and assign the value of nextInt into index i (0 - 4 for: par, golfer 1, golfer 2, golfer 3, golfer 4)

    I have to add the scores for each hole, 1-18, and add up the scores for par, golfer 1 etc. each line in the .txt file has to have 5 values: par, golfer1's score, golfer2's score etc. So, I have to add the scores from each column and assign the end value after 18 holes to each total.

    did I explain that correctly?

  17. #17
    sky
    sky is offline Member
    Join Date
    Nov 2009
    Posts
    96
    Rep Power
    0

    Default

    If you already know that the file has 18 lines you can add the counter, but if you don't know how many lines are in the file, the method hasNextLine() returns false when there is no more.

  18. #18
    rclausing is offline Member
    Join Date
    Oct 2009
    Location
    Oregon
    Posts
    22
    Rep Power
    0

    Default

    OK, I removed the counter loop as superfluous. However, I still get the runtime error and am not sure why.

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

    Default

    Quote Originally Posted by rclausing View Post
    That is confusing to me. Your first two pieces of code look identical, so why would one work and the other not?
    The first one checks to see if scanner has a next token via the hasNext() method. Then there's a call to nextInt(). What if there's a token available for reading but it's a String or double? For this to work you have to either check for a generic token via fileScan.hasNext() and then read a generic token in via fileScan.next() or check for an int via fileScan.hasNextInt() and then read in the next int via fileScan.nextInt(). Again, the check that starts with has MUST match the token read.

    The counting loop was to make sure the program would only instantiate 18 arrays, one for each hole.
    Hm, questionable to use that while (counter <= ...) loop

    ....
    did I explain that correctly?
    Yes, I think you did.

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

    Default

    Quote Originally Posted by rclausing View Post
    OK, I removed the counter loop as superfluous. However, I still get the runtime error and am not sure why.
    Did you run my code? That's a start on a better solution than you are trying. It's a big hint. Once you run it and see what is returned, you should be able to parse the Strings held by tokens and use them.

Page 1 of 2 12 LastLast

Similar Threads

  1. Please Help with Homework
    By theuser in forum Advanced Java
    Replies: 2
    Last Post: 07-30-2009, 03:37 PM
  2. help with homework
    By pinkdiamondgail in forum Advanced Java
    Replies: 7
    Last Post: 04-07-2009, 01:34 AM
  3. HELP Homework exercise
    By albi_87m in forum Java 2D
    Replies: 3
    Last Post: 04-04-2009, 05:10 AM
  4. Homework help...
    By robrobrob in forum New To Java
    Replies: 4
    Last Post: 10-17-2008, 04:24 AM
  5. Need help with homework.
    By JavaNewbie0000 in forum New To Java
    Replies: 2
    Last Post: 07-31-2008, 03:06 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
  •