Results 1 to 14 of 14
  1. #1
    xcaldk74 is offline Member
    Join Date
    Jan 2012
    Posts
    40
    Rep Power
    0

    Lightbulb Newbie Nested Loop Problem

    Hi Java Masters,

    So I was introduced to nested loops (loops inside the loops). My program will ask the user to pick a number from which pc will pick a number(guess game) and ask you to guess. After you guess it will tell you how many times it took for you to guess and "HERE IS MY PROBLEM" ask you if you want to play again.

    So far I was able to create the guess game BUT having troubles with getting to work yes/no. Please see my code below for any clues. I really wish NOT to get a straight answer.... Thank you in advance for all the inputs..... :)

    Java Code:
    import java.util.Scanner;
    import java.util.Random;
    
    public class hw7 
    {
    	public static void main(String[] args)
    	{
    		Scanner keyboard = new Scanner(System.in);
    		Random rand = new Random();
    		
    		int n;//number of the max guess options
    		int guess;//computer magic number of options
    		String reply, input;//asks user if want to play again
    		int count = 0;//number which will tell us how many times took to guess
    	
    		
    		
    		System.out.print("How big of number can I use? ");
    		n = keyboard.nextInt();
    		
    		guess = rand.nextInt(n)+1;//generate n amount of options to guess
    		
    		while (reply == 'Y')
    		{
    		 do
    		 {
    			 System.out.print("Guess a number from 1 to " + n + " ");
    			 guess = keyboard.nextInt();
    			
    			 if(guess>n)
    				 System.out.println("Try a lower number. ");
    			
    			 else if(guess<n)
    				 System.out.println("Try a higher number. ");
    				
    			 else
    			 	 System.out.println("Correct");
    			
    			 count ++;
    			
    		 }while (guess!=n);//end of do
    		
    		System.out.print("You guessed the number on attempt # " + count);
    		
    		System.out.print("Do you want to play again? (Y/N) : ");
    		input = keyboard.nextLine();
    		reply = input.chartAt(0);
    		
    		}//end of while
    		
    		
    		
    	}
    }
    OUTPUT:

    without second loop program works but after adding second these are my 2 ERROR MESSAGES:

    hw7.java:23: incomparable types: java.lang.String and char
    while (reply == 'Y')
    ^
    hw7.java:47: cannot find symbol
    symbol : method chartAt(int)
    location: class java.lang.String
    reply = input.chartAt(0);
    ^
    2 errors

    OUTPUT WITHOUT 2ND LOOP:


    ----jGRASP exec: java hw7
    How big of number can I use? 3
    Guess a number from 1 to 3 1
    Try a higher number.
    Guess a number from 1 to 3 2
    Try a higher number.
    Guess a number from 1 to 3 3
    Correct
    You guessed the number on attempt # 3
    ----jGRASP: operation complete.

  2. #2
    Jeff_H is offline Member
    Join Date
    Mar 2012
    Posts
    9
    Rep Power
    0

    Default Re: Newbie Nested Loop Problem

    reply is a String variable; 'Y' is a character literal. There's a handful of ways to compare the contents of a String variable. You could use reply.equals("Y"), or you could test a single character using reply.charAt(0) == 'Y'

    There's another slight issue I can see off-the-bat as well. The while loop is a pretest loop, meaning that if the condition doesn't exist from the start, the loop will never iterate. You could either initialize reply with "Y", or you could change the while loop to a do-while.

    I hope this helps.

  3. #3
    xcaldk74 is offline Member
    Join Date
    Jan 2012
    Posts
    40
    Rep Power
    0

    Default Re: Newbie Nested Loop Problem

    Quote Originally Posted by Jeff_H View Post
    reply is a String variable; 'Y' is a character literal. There's a handful of ways to compare the contents of a String variable. You could use reply.equals("Y"), or you could test a single character using reply.charAt(0) == 'Y'

    There's another slight issue I can see off-the-bat as well. The while loop is a pretest loop, meaning that if the condition doesn't exist from the start, the loop will never iterate. You could either initialize reply with "Y", or you could change the while loop to a do-while.

    I hope this helps.
    Hi Jeff,

    Thanks for your input. I've tried both reply.charAt(0) == 'Y' ^ reply.equals("Y") and in both cases getting this error:

    Do you want to play again? (Y/N) : Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(String.java:686)
    at hw7.main(hw7.java:47)


    What am I doing wrong? After the inner loop is done I print outcome of x amount of times till guessed and NOW asking the user to put yes/no where outer loop will go till reply == 'y'? Is the outer group constructed in a bad way or I'm missing something else?

    CODE:
    Java Code:
       import java.util.Scanner;
       import java.util.Random;
    
       public class hw7 
       {
          public static void main(String[] args)
          {
             Scanner keyboard = new Scanner(System.in);
             Random rand = new Random();
          
             int n;//number of the max guess options
             int guess;//computer magic number of options
             String input;//asks user if want to play again
             int count = 0;//number which will tell us how many times took to guess
          
             char reply;
          
          
             System.out.print("How big of number can I use? ");
             n = keyboard.nextInt();
          
             guess = rand.nextInt(n)+1;//generate n amount of options to guess
          
             do
             {
                do
                {
                   System.out.print("Guess a number from 1 to " + n + " ");
                   guess = keyboard.nextInt();
                
                   if(guess>n)
                      System.out.println("Try a lower number. ");
                   
                   else if(guess<n)
                      System.out.println("Try a higher number. ");
                   
                   else
                      System.out.println("Correct");
                
                   count ++;
                
                }while (guess!=n);//end of inner do
             
                System.out.println("You guessed the number on attempt # " + count);
                System.out.print("Do you want to play again? (Y/N) : ");
                input = keyboard.nextLine();
                reply = input.charAt(0);	
             	 
             }while (reply == 'Y');//outside loop

  4. #4
    xcaldk74 is offline Member
    Join Date
    Jan 2012
    Posts
    40
    Rep Power
    0

    Default Re: Newbie Nested Loop Problem

    just traced through my code and it appears that my main guess game is incorrect

  5. #5
    Jeff_H is offline Member
    Join Date
    Mar 2012
    Posts
    9
    Rep Power
    0

    Default Re: Newbie Nested Loop Problem

    move the lines:
    Java Code:
    System.out.print("How big of number can I use? ");
    n = keyboard.nextInt();
        
    guess = rand.nextInt(n)+1;//generate n amount of options to guess
    count = 0; //reset the counter after every game
    into the outer loop, but before the inner loop. You want the question "How big of a number can I use? " to be displayed every time, as well as the other three lines.

    I also changed line 46 to: input = keyboard.next();

    After those quick changes, the loops were working well for me Well, except for the slight logic error that makes the correct answer the highest possible number.

    How big of number can I use? 4
    Guess a number from 1 to 4 4
    Correct

    How big of number can I use? 3494
    Guess a number from 1 to 3494 3994
    Correct
    You're using n as the basis for comparison, and to determine the limiting number of the guessing game. n will always equal the number the user enters.

  6. #6
    xcaldk74 is offline Member
    Join Date
    Jan 2012
    Posts
    40
    Rep Power
    0

    Default Re: Newbie Nested Loop Problem

    NOW ive fixed the main code BUT still getting the same error with outside loop ? what am I missing?!?! can I do "do loop in do loop"?

    Java Code:
    import java.util.Scanner;
       import java.util.Random;
    
       public class hw7 
       {
          public static void main(String[] args)
          {
             Scanner keyboard = new Scanner(System.in);
             Random rand = new Random();
          
             int n;//number of the max guess options
             int guess;//computer magic number of options
             String input;//asks user if want to play again
             int count = 0;//number which will tell us how many times took to guess
          	int userGuess;
             char reply;
          
          
             System.out.print("How big of number can I use? ");
             n = keyboard.nextInt();
          
             guess = rand.nextInt(n)+1;//generate n amount of options to guess
          
             do
             {
                do
                {
                   System.out.print("Guess a number from 1 to " + n + " ");
                   userGuess = keyboard.nextInt();
                
                   if(userGuess>guess)
                      System.out.println("Try a lower number. ");
                   
                   else if(userGuess<guess)
                      System.out.println("Try a higher number. ");
                   
                   else
                      System.out.println("Correct");
                
                   count ++;
                
                System.out.println("You guessed the number on attempt # " + count);
                
                }while (userGuess!=guess);//end of inner do
             
             
                System.out.print("Do you want to play again? (Y/N) : ");
                input = keyboard.nextLine();
                reply = input.charAt(0);	
             	 
             }while (reply == 'Y');//outside loop

  7. #7
    xcaldk74 is offline Member
    Join Date
    Jan 2012
    Posts
    40
    Rep Power
    0

    Default Re: Newbie Nested Loop Problem

    Quote Originally Posted by Jeff_H View Post
    move the lines:
    Java Code:
    System.out.print("How big of number can I use? ");
    n = keyboard.nextInt();
        
    guess = rand.nextInt(n)+1;//generate n amount of options to guess
    count = 0; //reset the counter after every game
    into the outer loop, but before the inner loop. You want the question "How big of a number can I use? " to be displayed every time, as well as the other three lines.

    I also changed line 46 to: input = keyboard.next();

    After those quick changes, the loops were working well for me Well, except for the slight logic error that makes the correct answer the highest possible number.


    You're using n as the basis for comparison, and to determine the limiting number of the guessing game. n will always equal the number the user enters.
    yes Jeff, while I was tracing through the code I found out this was an issue. got it fixed now... what is wrong with my outside looP?

  8. #8
    xcaldk74 is offline Member
    Join Date
    Jan 2012
    Posts
    40
    Rep Power
    0

    Default Re: Newbie Nested Loop Problem

    Java Code:
     System.out.print("Do you want to play again? (Y/N) : ");
                input = keyboard.nextLine();
                reply = input.charAt(0);    
                  
             }while (reply == 'Y');//outside loop
    isn't that should ask the user to put y OR n and the DO LOOP will run till reply == 'y' where is the logic i'm missing.... new to loops :(

  9. #9
    Jeff_H is offline Member
    Join Date
    Mar 2012
    Posts
    9
    Rep Power
    0

    Default Re: Newbie Nested Loop Problem

    Java Code:
    import java.util.Scanner;
       import java.util.Random;
     
       public class hw7 
       {
          public static void main(String[] args)
          {
             Scanner keyboard = new Scanner(System.in);
             Random rand = new Random();
           
             int n;//number of the max guess options
             int guess;//computer magic number of options
             String input;//asks user if want to play again
             int count = 0;//number which will tell us how many times took to guess
            int userGuess;
             char reply;
           
             do
             {
                 System.out.print("How big of number can I use? ");
                n = keyboard.nextInt();
           
                guess = rand.nextInt(n)+1;//generate n amount of options to guess
                count = 0; //reset the counter after each game
                do
                {
                   System.out.print("Guess a number from 1 to " + n + " ");
                   userGuess = keyboard.nextInt();
                 
                   if(userGuess>guess)
                      System.out.println("Try a lower number. ");
                    
                   else if(userGuess<guess)
                      System.out.println("Try a higher number. ");
                    
                   else
                      System.out.println("Correct");
                 
                   count ++;
                 
                System.out.println("You guessed the number on attempt # " + count);
                 
                }while (userGuess!=guess);//end of inner do
              
              
                System.out.print("Do you want to play again? (Y/N) : ");
                input = keyboard.next();
                reply = input.charAt(0);    
                  
             }while (reply == 'Y');//outside loop
          }
       }
    I moved a few lines and added count = 0; to the outer loop to reset after each game. I also changed input = keyboard.nextLine(); to input = keyboard.next();. It's working for me.

    I understand your frustration completely if you need me to explain why I made the changes I did, feel free to ask.
    Last edited by Jeff_H; 03-06-2012 at 04:14 AM.

  10. #10
    xcaldk74 is offline Member
    Join Date
    Jan 2012
    Posts
    40
    Rep Power
    0

    Default Re: Newbie Nested Loop Problem

    Jeff,

    Why did you change input = keyboard.nextLine(); to input = keyboard.next(); ???? - my wild guess would be since I've specified that input is String I don't need "Line" or what???

  11. #11
    xcaldk74 is offline Member
    Join Date
    Jan 2012
    Posts
    40
    Rep Power
    0

    Default Re: Newbie Nested Loop Problem

    I also had to move System.out.println("You guessed the number on attempt # " + count); OUTSIDE of the while because otherwise it would print SOP where it NOT supposed to. so why did nextLine VS next makes a difference?

  12. #12
    xcaldk74 is offline Member
    Join Date
    Jan 2012
    Posts
    40
    Rep Power
    0

    Default Re: Newbie Nested Loop Problem

    My Final Code:

    Java Code:
       import java.util.Scanner;
       import java.util.Random;
    
       public class hw7 
       {
          public static void main(String[] args)
          {
             Scanner keyboard = new Scanner(System.in);
             Random rand = new Random();
          
             int n;//number of the max guess options
             int guess;//computer magic number of options
             String input;//asks user if want to play again
             int count = 0;//number which will tell us how many times took to guess
             int userGuess;
             char reply;
          
          
             do
             {
                System.out.print("How big of number can I use? ");
                n = keyboard.nextInt();   
                guess = rand.nextInt(n)+1;//generate n amount of options to guess
                count = 0;
             	 
                do
                {
                   System.out.print("Guess a number from 1 to " + n + " ");
                   userGuess = keyboard.nextInt();
                
                   if(userGuess>guess)
                      System.out.println("Try a lower number. ");
                   
                   else if(userGuess<guess)
                      System.out.println("Try a higher number. ");
                   
                   else
                      System.out.println("Correct");
                
                   count ++;
                
                
                }while (userGuess!=guess);//end of inner do
                System.out.println("You guessed the number on attempt # " + count);
                
                System.out.print("Do you want to play again? (Y/N) : ");
                input = keyboard.nextLine();
                reply = input.charAt(0);	
             	 
             }while (reply == 'Y');//outside loop
          		
          
          
          }
       }

  13. #13
    Jeff_H is offline Member
    Join Date
    Mar 2012
    Posts
    9
    Rep Power
    0

    Default Re: Newbie Nested Loop Problem

    Because keyboard.nextLine() sees the white space (the enter, return, or carriage return. whichever term you prefer) that occurs when the user enters a guess. I might be a little off on my explanation, but if you would like a visual example of this, try running:

    Java Code:
    import java.util.Scanner;
       import java.util.Random;
     
       public class HW7 
       {
          public static void main(String[] args)
          {
             Scanner keyboard = new Scanner(System.in);
             Random rand = new Random();
           
             int n;//number of the max guess options
             int guess;//computer magic number of options
             String input;//asks user if want to play again
             int count = 0;//number which will tell us how many times took to guess
            int userGuess;
             char reply;
           
             do
             {
                 System.out.print("How big of number can I use? ");
                n = keyboard.nextInt();
           
                guess = rand.nextInt(n)+1;//generate n amount of options to guess
                count = 0; //reset the counter after each game
                do
                {
                   System.out.print("Guess a number from 1 to " + n + " ");
                   userGuess = keyboard.nextInt();
                 
                   if(userGuess>guess)
                      System.out.println("Try a lower number. ");
                    
                   else if(userGuess<guess)
                      System.out.println("Try a higher number. ");
                    
                   else
                      System.out.println("Correct");
                 
                   count ++;
                 
                System.out.println("You guessed the number on attempt # " + count);
                 
                }while (userGuess!=guess);//end of inner do
              
              
                System.out.print("Do you want to play again? (Y/N) : ");
                input = keyboard.nextLine(); //replaced keyboard.next() with two .nextLine()'s
                input = keyboard.nextLine();
                reply = input.charAt(0);  
                  
             }while (reply == 'Y');//outside loop
          }
       }
    You'll find that it runs the same as a single .next()

  14. #14
    xcaldk74 is offline Member
    Join Date
    Jan 2012
    Posts
    40
    Rep Power
    0

    Default Re: Newbie Nested Loop Problem

    [QUOTE=Jeff_H;269824]Because keyboard.nextLine() sees the white space (the enter, return, or carriage return. whichever term you prefer) that occurs when the user enters a guess. I might be a little off on my explanation,/QUOTE]

    yes still little bit confused.... :( Thx a bunch for all of your HELP JEFF

Similar Threads

  1. Nested for loop problem.
    By Hello in forum New To Java
    Replies: 7
    Last Post: 11-03-2011, 06:06 PM
  2. Nested loop problem
    By jim01 in forum New To Java
    Replies: 0
    Last Post: 04-17-2011, 04:38 AM
  3. Nested Loop
    By sehudson in forum New To Java
    Replies: 2
    Last Post: 03-11-2011, 04:39 AM
  4. can some one help me with nested loop?
    By keycoffee in forum New To Java
    Replies: 10
    Last Post: 01-25-2010, 03:49 AM
  5. Nested For Loop
    By yuchuang in forum New To Java
    Replies: 1
    Last Post: 07-08-2007, 02:11 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
  •