Results 1 to 3 of 3

Thread: ]

  1. #1
    SamJava_the_Hut is offline Senior Member
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    100
    Rep Power
    0

    Default ]

    I'm trying to create a while loop that will exit when the user input matches a hard coded string:
    Java Code:
    package randomExperiments;
    
    import java.util.Scanner;
    import java.lang.Double;
    import java.text.NumberFormat;
    import java.lang.Integer;
    
    public class RandomExperiments {
    	
    	public static void main(String[] args){
    				
    		//Comparing Strings
    		String python = "Python";		
    		String guess = "";
    		System.out.println("You're not going anywhere until you guess what the 2nd best programming language in the world is!");
    		while(!guess.equals(python)){
    			//Scanner input = new Scanner(System.in);
    			//guess = input.nextLine();
    			if(guess.equalsIgnoreCase(python)){
    				break;
    			}else{
    				System.out.println("Nope! Guess again.");
    				Scanner input = new Scanner(System.in);
    				guess = input.nextLine();
    			}
    		}
    	}
    }
    But instead of taking in new input, it keeps telling me to guess again, then when I try to enter the guess, the program terminates:
    ]-whileloop01.png

    Why does that happen?

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

    Default Re: How to exit a while loop with user input and string comparisons?

    Try debugging the code by printing out the contents of guess with the "Nope! Guess again." message so you can see what the computer sees.

    You should only define one instance of the Scanner class outside of the loop.
    If you don't understand my response, don't ignore it, ask a question.

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

    Default Re: How to exit a while loop with user input and string comparisons?

    The program works for me.
    First it prints, "Nope! Guess again."

    After that it continues to loop and print the error message until I enter python.

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

Posting Permissions

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