Results 1 to 10 of 10
  1. #1
    iriscience is offline Member
    Join Date
    Jan 2011
    Location
    Ohio
    Posts
    11
    Rep Power
    0

    Default [Q] Loop issue (while loop)

    I posted earlier today about generating a random letter and you guys were awesome for answering so fast! I ran into another impasse while making my guessing game for my programming class and was hoping you guys would be able to help me with this one too. This game is just supposed to allow the player to guess at a randomly generated letter 4 times. My book showed a simple while loop statement, so I thought I could pretty much copy the code. But I keep getting syntax errors. I'll point these out in the code. I know I can change it to a do-while or a for loop, but I'd really like to know why my while loop isn't working. Thanks so much for all your help guys!

    Java Code:
     //Prompt player for first guess
          System.out.print("You have 4 guesses to pick the letter, enter "
                  + "your guess: ");
          input = playerInput.nextLine();
    
          //Compare the player's guess to the random letter
          guess = input.compareToIgnoreCase(randomLetter);
    
          numberOfGuesses = 0;
          while (numberOfGuesses < 5)
          {
             if (guess == 0)
                System.out.println("Congratulations! You win!");
                break;
             else if (guess > 0)  [B][COLOR="Red"]<< I get a syntax error here saying "else without if">>[/COLOR][/B]
                System.out.println("Your guess is alphabetically after the "
                        + "random letter, try again.");
             else
                System.out.println("Your guess is alphabetically before the "
               + "random letter, try again.");
             numberOfGuesses++;
          }
    ps: I initialized all variables at the beginning of my program as per my instructors formatting guidelines.

  2. #2
    mine0926 is offline Senior Member
    Join Date
    Apr 2010
    Location
    Philippines
    Posts
    580
    Rep Power
    5

    Default

    Add curly braces on your if..else statements
    EXAMPLE:
    Java Code:
        if(i == 0)
        [b]{[/b]
                System.out.println("i is equals to ZERO(0)")
        [b]}[/b]
        else if(i == 1)
        [b]{[/b]
                System.out.println("i is equals to ONE(1)")
        [b]}[/b]

  3. #3
    iriscience is offline Member
    Join Date
    Jan 2011
    Location
    Ohio
    Posts
    11
    Rep Power
    0

    Default

    I tried adding those in earlier tonight thinking they could be the issue, but it doesn't change the error. I don't know what could be the issue! I'm going to give up for the night and hopefully I'll have an epiphany in the morning. :)

  4. #4
    mine0926 is offline Senior Member
    Join Date
    Apr 2010
    Location
    Philippines
    Posts
    580
    Rep Power
    5

    Default

    copy-paste your code (with curly braces on if..else statements, as what I have stated before) and the complete error message.
    I dont see any error aside from the missing curly braces.

    GoodLuck!

  5. #5
    iriscience is offline Member
    Join Date
    Jan 2011
    Location
    Ohio
    Posts
    11
    Rep Power
    0

    Default

    Java Code:
    /*
     * This program will initiate a guessing game. The player will be prompted
     * to guess the correct letter.
     */
    package w004dca;
    
    /**
     * @author my name
     * class
     * ta's name
     * instructor's name
     */
    import java.util.Scanner;
    
    public class Main
    {
    
       /**
        * This program will first explain the rules to the player. It will
        * then generate a random capital letter from A to Z. The program
        * will then prompt the player to guess the random letter. If the
        * guess is incorrect, the program will ask the player to make another
        * attempt. The program will also inform the player whether their 
        * guess was above or below the randomly generated letter. If the 
        * player is correct with any of the guesses, the program will
        * congratulate the player and prompt for another game. The total 
        * number of guesses allotted will not exceed four.
        * @param args the command line arguments
        */
       public static void main(String[] args)
       {
    
          //Create a scanner object
          Scanner playerInput = new Scanner(System.in);
    
          //Declare Constants
    
          //Declare Variables
          int num;
          int numberOfGuesses;
          int guess;
          String input;
          String randomLetter;
    
          
          //Show rules to the player
          System.out.println("The purpose of this program is to play a "
                  + "guessing game. In the game the program picks a random "
                  + "capital letter (A-Z) and the player is given up to four "
                  + "tries to guess the letter. The player may input a lower "
                  + "or upper case letter. Once a game is over the program "
                  + "asks if additional games are to be played. When no more "
                  + "games are to be played a total score of wins for the "
                  + "computer and the player is displayed.");
          
          //Generate a random capital letter
          String[] letters = {"A","B","C","D","E","F","G","H","I","J","K",
             "L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
          num = (int)(Math.random() * 26);
          randomLetter = letters[num];
          System.out.println(num);
          System.out.println(randomLetter);
    
          //Display beginning of game message
          System.out.println("The game has begun. The computer has chosen "
                  + "a letter.");
    
           //Prompt player for first guess
          System.out.print("You have 4 guesses to pick the letter, enter "
                  + "your guess: ");
          input = playerInput.nextLine();
    
          //Compare the player's guess to the random letter
          guess = input.compareToIgnoreCase(randomLetter);
    
          numberOfGuesses = 0;
          while (numberOfGuesses < 5) 
          {
             if (guess == 0)
             {
                System.out.println("Congratulations! You win!");
             }
                break;
             else if (guess > 0)    [COLOR="red"][B]<<'else' without 'if'>>[/B][/COLOR]
                {
                System.out.println("Your guess is alphabetically after the "
                        + "random letter, try again.");
                }
              else   [COLOR="red"][B]<<illegal start of type>>[/B][/COLOR]
           {
                System.out.println("Your guess is alphabetically before the "
               + "random letter, try again.");
           }
             numberOfGuesses++;   [COLOR="Red"][B]<<cannot find symbol>>[/B][/COLOR]
          }
         }
    }
    BTW, thanks so much for your help!

  6. #6
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Your error is that you break out of the loop after the if clause which is incorrect, you also do something similar which is incorrect after the else clause. The reason for adding curly braces is so you can add a statement block. An if or else can either have a single statement, or a statement block.

  7. #7
    Vase is offline Member
    Join Date
    Jan 2011
    Location
    Gainesville, FL
    Posts
    45
    Rep Power
    0

    Default

    Java Code:
    while (numberOfGuesses < 4) {
             if (guess == 0) {
                 System.out.println("Congratulations! You win!");
                 numberOfGuesses = 4;
             }
             else if (guess > 0) {
                 System.out.println("Your guess is alphabetically after the "
                        + "random letter, try again.");
                 numberOfGuesses++;
             }
             else {
                System.out.println("Your guess is alphabetically before the "
                     + "random letter, try again.");
                numberOfGuesses++;
             }
    }
    Generally the 'break' command is taught as poor programming (unless you're using a switch statement). There is no need for it here, so it's better off NOT here. numberOfGuesses will increase by 1 each time the user guesses it wrong, but will also provide the sentinel value to end the loop if the user guesses it right.

    Also note that if numberOfGuesses begins at 0, it should end < 4, not < 5 (If you only want to allow 4 guesses).


    I will let you know now though, this is going to need to be fixed up. The user is never prompted to make another guess.

  8. #8
    iriscience is offline Member
    Join Date
    Jan 2011
    Location
    Ohio
    Posts
    11
    Rep Power
    0

    Default

    Thank you so much for your quick answers guys!
    @Vase: Thanks for letting me know about the break commands! I literally just started learning Java a few weeks ago, so breaking it down like that is exactly what I need! Thank you again! And I know I still have a ways to go on this, I was just really stuck and couldn't figure out where I was going wrong. This forum is kick ass! :D

  9. #9
    Vase is offline Member
    Join Date
    Jan 2011
    Location
    Gainesville, FL
    Posts
    45
    Rep Power
    0

    Default

    You're welcome, I hope I helped.

    I'm also only 4 weeks into my first Java course—albeit on top of learning C, so I have some programming experience. By helping you, I am also helping myself get more acquainted with it, so I enjoy it (although there may be better ways to do things in Java that I don't know yet).

  10. #10
    iriscience is offline Member
    Join Date
    Jan 2011
    Location
    Ohio
    Posts
    11
    Rep Power
    0

    Default

    You definitely helped! I'm really close to being done and that piece of code was making me so mad! :)

Similar Threads

  1. Convert do while loop to for loop
    By sandeeptheviper in forum New To Java
    Replies: 3
    Last Post: 01-03-2011, 01:37 PM
  2. Replies: 5
    Last Post: 04-30-2010, 06:05 PM
  3. while-loop stopping on first loop
    By davester in forum New To Java
    Replies: 6
    Last Post: 06-26-2009, 09:46 PM
  4. while loop help
    By kathyla18 in forum New To Java
    Replies: 1
    Last Post: 03-02-2009, 07:49 PM
  5. While loop
    By sjhentges in forum New To Java
    Replies: 11
    Last Post: 11-04-2008, 05:26 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
  •