Page 1 of 2 12 LastLast
Results 1 to 20 of 24
Like Tree1Likes

Thread: Loop problems!

  1. #1
    jgarner is offline Member
    Join Date
    Jul 2015
    Posts
    11
    Rep Power
    0

    Default Loop problems!

    Hey ladies and gents! Justin back with more dummy questions! So I'm starting to get into control statements and I'm trying to experiment again. This time I wrote my first game! Do me a favor and imagine Doom and Battlefield with a mixture of Tomb Raider. Got it in your head? Great. This is the complete opposite of anything like that. I'm just trying to write a command line program that lets you guess which letter the computer guessed. You keep guessing until you get it right. When you get it right, it congratulates you and tells you how many times you tried to get it right. Pretty simple concept I thought..

    So I have two known issues with the code.

    1) it repeats the, for lack of better terms, "retry statement" twice. I can't figure out why it prints it twice before you can input your new guess.

    2) the counter isn't working correctly. It you try 3 times to get it correct. It tells me it tried 5 times. If I try 3 times, it tells me it tried 5 times.


    Here's the code. Hopefully someone can give me some explanation as to what I'm doing incorrectly. Thanks in advance for all the help!


    Here is some sample output.....

    Java Code:
    justin@justin-VPCCW17FX:~/java$ java Guess
    I'm thinking of a letter between A and Z and capitalization matters!
    Can you guess it?
    Please type your guess then press ENTER
    a
    Please guess again!
    Press ENTER after new guess 
    Please guess again!
    Press ENTER after new guess 
    t
    Please guess again!
    Press ENTER after new guess 
    Please guess again!
    Press ENTER after new guess 
    K
    You guessed right! Who would have thought? K was the answer, and it only took you 4 times to figure it out. The odds of you guessing right were 1 in 52!



    Here is my crappy code!

    Java Code:
    // make a simple command based game. Try to guess the computer's choice!
    
    class Guess {
    
    public static void main(String args[])
      throws java.io.IOException   {    // must use because of System.in.read command
    
    char ch, answer = 'K';
    int tries = 1; 
    
    
    System.out.println("I'm thinking of a letter between A and Z and capitalization matters!\nCan you guess it?\nPlease type your guess then press ENTER");
    ch = (char) System.in.read();
    
    
    
    //Loop to keep guessing until correct. This is where I am most confused. My thought process is that while user guess isn't equal to the answer. run the loop until it is. Keep a counter of attempts.
    	while(ch != answer) {
    	    System.out.println("Please guess again!\nPress ENTER after new guess ");
                ch = (char) System.in.read();
    	    ++tries;
    	}
    
    
    
    // Once user guess is correct, skip down to this and end the program..
    tries= tries - 1; 
    System.out.println("You guessed right! Who would have thought? " + answer + " was the answer, and it only took you " + tries + " times to figure it out. The odds of you guessing right were 1 in 52!");
    
    
      }
    }


    Again, thanks for any help I get!

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: Loop problems!

    Add a print statement to print out the character that is read so you can see what the computer sees when the code is executed.

    The read() method is low level and returns what the keyboard sends to the program without any filtering.
    The Enter key sends some values that are not expected.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    jgarner is offline Member
    Join Date
    Jul 2015
    Posts
    11
    Rep Power
    0

    Default Re: Loop problems!

    Quote Originally Posted by Norm View Post
    Add a print statement to print out the character that is read so you can see what the computer sees when the code is executed.

    The read() method is low level and returns what the keyboard sends to the program without any filtering.
    The Enter key sends some values that are not expected.


    When you said that, I was thinking that maybe ENTER was throwing a crazy value into 'ch'. Honestly, I don't see any difference based off what you said..



    Here is me replicating my last attempt.. Assuming I'm not forcing an error/memory/data issue that I'm blind to to something it looks redundant printing the user input. Could you please elaborate on this or get me in the right direction?

    Java Code:
    justin@justin-VPCCW17FX:~/java$ java Guess
    I'm thinking of a letter between A and Z and capitalization matters!
    Can you guess it?
    Please type your guess then press ENTER
    a
    You entered: a
    Please guess again!
    Press ENTER after new guess 
    You entered: 
    
    Please guess again!
    Press ENTER after new guess 
    t
    You entered: t
    Please guess again!
    Press ENTER after new guess 
    You entered: 
    
    Please guess again!
    Press ENTER after new guess 
    K
    You entered: K
    You guessed right! Who would have thought? K was the answer, and it only took you 4 times to figure it out. The odds of you guessing right were 1 in 52!


    Here is the code as I changed it off what you said.

    Java Code:
    // make a simple command based game. Try to guess the computer's choice!
    
    class Guess {
    
    public static void main(String args[])
      throws java.io.IOException   {    // must use because of System.in.read command
    
    char ch, answer = 'K';
    int tries = 1; 
    
    
    System.out.println("I'm thinking of a letter between A and Z and capitalization matters!\nCan you guess it?\nPlease type your guess then press ENTER");
    ch = (char) System.in.read();
    System.out.println("You entered: " + ch);
    
    
    //Loop to keep guessing until correct. This is where I am most confused. My thought process is that while user guess isn't equal to the answer. run the loop until it is. Keep a counter of attempts.
    	while(ch != answer) {
    	    System.out.println("Please guess again!\nPress ENTER after new guess ");
                ch = (char) System.in.read();
    	    System.out.println("You entered: " + ch);
    	    ++tries;
    	}
    
    
    
    // Once user guess is correct, skip down to this and end the program..
    tries= tries - 1; 
    System.out.println("You guessed right! Who would have thought? " + answer + " was the answer, and it only took you " + tries + " times to figure it out. The odds of you guessing right were 1 in 52!");
    
    
      }
    }

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Loop problems!

    Here is a hint. For most keys on a keyboard, each key generates a single character. And some characters can't be seen. How many keys do you type when you enter a letter to the program? It may not be obvious if you are new to programming.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  5. #5
    jgarner is offline Member
    Join Date
    Jul 2015
    Posts
    11
    Rep Power
    0

    Default Re: Loop problems!

    Quote Originally Posted by jim829 View Post
    Here is a hint. For most keys on a keyboard, each key generates a single character. And some characters can't be seen. How many keys do you type when you enter a letter to the program? It may not be obvious if you are new to programming.

    Regards,
    Jim
    I'm guessing that you are referring to the ENTER? This is my first programming language. I've done basic stuff with C++ several years back, but only on a entry level and never made any real programs.

    I'm aware that each key has a value like

    "A" = 65 in Decimal = 01000001 in binary


    But I'm almost definitely sure that you're referring to this section of code....
    Java Code:
            System.out.println("Please guess again!\nPress ENTER after new guess ");
                ch = (char) System.in.read();
            System.out.println("You entered: " + ch);
            ++tries;
    If so, I'm completely missing your points. Is there a term or concept I should be aware of?

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Loop problems!

    Quote Originally Posted by jgarner View Post
    "A" = 65 in Decimal = 01000001 in binary
    Correct.
    And what does 13 represent in ASCII (for example)?

    You can avoid this, of course, and simply use a Scanner, passing in the Sysem.in to the constructor. It has a readLine method, that would suit your needs and remove the immediate problem.

    As Norm says, read() is very low level.

    (I would normally suggest a BufferedReader in this case, but there's an extra step involved to getting it to work. I'm not fan of Scanner.)
    gimbal2 likes this.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Loop problems!

    Quote Originally Posted by Tolls View Post
    (I would normally suggest a BufferedReader in this case, but there's an extra step involved to getting it to work. I'm not fan of Scanner.)
    That. What extra step are you talking about? The need for an InputStreamReader?
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Loop problems!

    Quote Originally Posted by gimbal2 View Post
    That. What extra step are you talking about? The need for an InputStreamReader?
    Yes, that one.
    I started writing "use BufferedReader" then realised I'd need to explain about wrapping of streams and readers, otherwise I'd just be handing over code.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  9. #9
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Loop problems!

    IMO: the fear of spoonfeeding is too deep. No, you don't need to explain all that yet when the focus is on learning how to work with text data.

    Looky what I wrote here at the bottom:

    http://www.java-forums.org/new-java/...it-string.html

    Is that really so bad?
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Loop problems!

    Yes...it's awful and you should be ashamed...

    Go stand in the corner!
    :)
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  11. #11
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Loop problems!

    Whatever, its the cool corner where people are not afraid to post mere cookie cutter snippets of code. I'm glad to stand in it.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  12. #12
    jgarner is offline Member
    Join Date
    Jul 2015
    Posts
    11
    Rep Power
    0

    Default Re: Loop problems!

    Quote Originally Posted by Tolls View Post
    Correct.
    And what does 13 represent in ASCII (for example)?

    You can avoid this, of course, and simply use a Scanner, passing in the Sysem.in to the constructor. It has a readLine method, that would suit your needs and remove the immediate problem.

    As Norm says, read() is very low level.

    (I would normally suggest a BufferedReader in this case, but there's an extra step involved to getting it to work. I'm not fan of Scanner.)


    13 represents the "ENTER" key? So if I understand this correctly, the below line is reading the "input + ENTER" each time? Then ch, being type char can only hold one value? So it's too much data for it? From my data type table, char is the only Unicode type? If I use Scanner, it can properly read the input without the ENTER command interfering? Scanner is a type right? So I would do Scanner = ch; ? What is the difference in that, and using String?

    Java Code:
      ch = (char) System.in.read();

    Also, what is causing my output to print twice? Is it because it's reading the input as one and the ENTER as a second one?

  13. #13
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    12,059
    Rep Power
    25

    Default Re: Loop problems!

    Quote Originally Posted by jgarner View Post
    Also, what is causing my output to print twice? Is it because it's reading the input as one and the ENTER as a second one?
    You're spot on.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  14. #14
    jgarner is offline Member
    Join Date
    Jul 2015
    Posts
    11
    Rep Power
    0

    Default Re: Loop problems!

    Quote Originally Posted by DarrylBurke View Post
    You're spot on.

    db

    OK, so I had to go do some research on the Scanner class to try to adjust my code accordingly. So after some tries, I've gotten it down to this broken code below. It's having problems with my while loop, specifically on my variable names on lines 23/24. It is saying they are declared already in the main function. Do I need to declare these variable as some sort of public variable? Do I need to add new variables in the while loop?

    Basically I'm lost with broken code. S.O.S


    Java Code:
    // make a simple command based game. Try to guess the computer's choice!
    
    import java.util.Scanner;  								  //need this to run Scanner.
    
    class Guess {
    public static void main(String args[])
      throws java.io.IOException   {    					// must use because of System.in.read command
    
    char answer = 'K';
    int tries = 1; 
    
    
    System.out.println("I'm thinking of a letter between A and Z and capitalization matters!\nCan you guess it?\nPlease type your guess then press ENTER");
    Scanner scan = new Scanner(System.in);
    String inputvar = scan.nextLine();
    	System.out.println("You entered: " + inputvar);
    
    							/*Loop to keep guessing until correct. This is where I am most confused. My thought process is that while								 user guess isn't equal	 to the answer. run the loop until it is. Keep a counter of attempts.*/	
    
    
    while(scan != answer) {
    	    System.out.println("Please guess again!\nPress ENTER after new guess ");
                Scanner scan = new Scanner(System.in);
    	    String inputvar = scan.nextLine();
    		System.out.println("You entered: " + inputvar);
    	    ++tries;
    	}
    
    
    
    // Once user guess is correct, skip down to this and end the program..
    tries= tries - 1; 
    System.out.println("You guessed right! Who would have thought? " + answer + " was the answer, and it only took you " + tries + " times to figure it out. The odds of you guessing right were 1 in 52!");
    
    
      }
    }

    Any new advice?

  15. #15
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Loop problems!

    You only need one instance of the Scanner class so remove the one in the while loop. And you are re-declaring the String. All you need to do is assign to it.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  16. #16
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Loop problems!

    Quote Originally Posted by jim829 View Post
    And you are re-declaring the String. All you need to do is assign to it.
    @jgarner: see the picture in post #3 of this thread if you don't know what Jim is babbling about here ;)
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  17. #17
    jgarner is offline Member
    Join Date
    Jul 2015
    Posts
    11
    Rep Power
    0

    Default Re: Loop problems!

    Quote Originally Posted by jim829 View Post
    You only need one instance of the Scanner class so remove the one in the while loop. And you are re-declaring the String. All you need to do is assign to it.

    Regards,
    Jim

    Java Code:
    // make a simple command based game. Try to guess the computer's choice!
    
    import java.util.Scanner;  								  //need this to run Scanner.
    
    class Guess {
    public static void main(String args[])
      throws java.io.IOException   {    					// must use because of System.in.read command
    
    char answer = 'K';
    int tries = 1; 
    
    
    System.out.println("I'm thinking of a letter between A and Z and capitalization matters!\nCan you guess it?\nPlease type your guess then press ENTER");
    Scanner scan = new Scanner(System.in);
    String inputvar = scan.nextLine();
    	System.out.println("You entered: " + inputvar);
    
    							/*Loop to keep guessing until correct. This is where I am most confused. My thought process is that while								 user guess isn't equal	 to the answer. run the loop until it is. Keep a counter of attempts.*/	
    
    
    while(scan != answer) {
    	    System.out.println("Please guess again!\nPress ENTER after new guess ");
                //scan = new Scanner(System.in);
    	   /* String*/ inputvar = scan.nextLine();
    		System.out.println("You entered: " + inputvar);
    	    ++tries;
    	}
    
    
    
    // Once user guess is correct, skip down to this and end the program..
    tries= tries - 1; 
    System.out.println("You guessed right! Who would have thought? " + answer + " was the answer, and it only took you " + tries + " times to figure it out. The odds of you guessing right were 1 in 52!");
    
    
      }
    }

    I'm now getting errors with declaring the variable type? I don't quite understand what you're saying. Am I stupid or is there a lack of good material available on this?

  18. #18
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: Loop problems!

    I'm now getting errors
    Please copy the full text of the error message and paste it here. It has important info about the error.
    If you don't understand my response, don't ignore it, ask a question.

  19. #19
    Join Date
    Aug 2015
    Location
    Northern California
    Posts
    31
    Rep Power
    0

    Default Re: Loop problems!

    jgarner are you sure you meant to do this or did you perhaps have an error here? If you have an internal error you don't understand read it to us.
    Java Code:
    while(scan != answer)
    Added:
    Look at this example using numbers. As it was explained earlier in the thread numbers represent each letter anyway so you can use Random to generate a number within the range from a-z A-Z, or use equalsIgnoreCase() to make life simpler
    http://www.java-made-easy.com/guessing-game.html
    Last edited by devMichaelSmith; 08-11-2015 at 08:47 AM.

  20. #20
    jgarner is offline Member
    Join Date
    Jul 2015
    Posts
    11
    Rep Power
    0

    Default Re: Loop problems!

    Quote Originally Posted by Norm View Post
    Please copy the full text of the error message and paste it here. It has important info about the error.
    The error is...

    Java Code:
    justin@justin-VPCCW17FX:~/java$ javac Guess.java
    Guess.java:21: error: incomparable types: Scanner and char
    while(scan != answer) {
               ^
    1 error

    What am I doing wrong? I'm doing this on my own and not for school so I don't have any other help than this forum. Also, I'm still really confused on the Scanner class. Specifically this line below confuses me. Can someone elaborate like I'm an idiot.

    Java Code:
    Scanner scan = new Scanner(System.in);
    String inputvar = scan.nextLine();

Page 1 of 2 12 LastLast

Similar Threads

  1. Loop problems
    By amzers in forum New To Java
    Replies: 23
    Last Post: 08-16-2011, 07:18 PM
  2. Problems with While loop execution
    By Kevinius in forum New To Java
    Replies: 12
    Last Post: 03-03-2011, 07:35 AM
  3. Try catch loop problems :'(
    By Romally in forum New To Java
    Replies: 7
    Last Post: 11-17-2010, 08:15 PM
  4. Loop problems
    By jim01 in forum New To Java
    Replies: 3
    Last Post: 10-18-2010, 12:49 AM
  5. Problems with while loop
    By Albert in forum New To Java
    Replies: 2
    Last Post: 07-04-2007, 07:19 AM

Posting Permissions

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