Using a do-while loop to check a User's input in Java

24,192

Solution 1

Change it to

...
String input;
do
{
    input = scan.next();
    if(input.equals("enter") || input.equals("Enter"))
    {
        System.out.println("You have entered the house.");
    }
...

Solution 2

Just FYI, instead of:

if(input.equals("enter") || input.equals("Enter"))

use

input.equalsIgnoreCase("enter")

It will eliminate your "or" clauses and shorten your code a little bit

Share:
24,192

Related videos on Youtube

Zampanò
Author by

Zampanò

Updated on October 17, 2020

Comments

  • Zampanò
    Zampanò over 3 years

    I am trying to create a short text-based adventure game using java.

    I am a beginning programmer, so my methods may not be the most efficient, but I am using only what I have learned from my school courses so far.

    My problem occurs after asking the user for their input.

    import java.util.Scanner;
    public class House
    {
        public static void main(String[]args)
        {
    
            System.out.println("You have just moved into your new house.");
            System.out.println("What do you do next?");
            Scanner scan = new Scanner(System.in);
            String input = scan.next();
    
            do
            {
                if(input.equals("enter") || input.equals("Enter"))
                {
                    System.out.println("You have entered the house.");
                }
    
                else if(input.equals("leave") || input.equals("Leave"))
                {
                    System.out.println("You left and never came back.");
                    System.out.println("The End");
                    System.exit(0);
                }
    
                else
                {
                    System.out.println("I don't know how to "+input);
                    System.out.println("Try again");
                    System.out.println("What do you do next?");
                    input = scan.nextLine();
                }
            }
            while(!input.equals("enter") || !input.equals("Enter") || !input.equals("leave") || !input.equals("Leave"));
    
        }
    }
    

    The program works as expected if the user enters "leave", "Leave", or an unknown command. The problem occurs when the user enters "enter" or "Enter"

    The condition in my do-while loop should make the program exit the loop whenever their input is equal to "enter" or "Enter", but the program gets stuck in an endless loop instead.

    The program will simply repeat, "You have entered the house." over and over.

    Why is this problem occuring? I have no clue what I am doing wrong.

    Thanks!