0

Hello and thank you in advance for your time. I'm working on a homework assignment that require an input from the user in command line. If the user input the "Exit" or "Quit" My program should quit. I'm able to do one one work but not sure how to do two. ALso the my loop is not looping all time. Can someone shine some light please.

import java.io.Console;
public class Echo2{
    public static void main(String [] args){
    String userText = System.console().readLine("Enter some text:"); 
    //System.out.println("*** " + userText + " ***"  );
    if (userText.equals("Exit")){ 
        return;
    }
        else{
        System.out.println("*** " + userText + " ***"  );


        }

    }
}
0

2 Answers 2

3

As of the loop you can simply do this:

while(true) {
    if (userText.equals("Exit") || userText.equals("Quit")) {
        break;
    }  
}

Or if you want to go a little fancy here you can do this

 while(true) {
        if ("exit".equals(userText.toLowerString()) || "quit".equals(userText.toLowerString()) {
            break;
        }  
  }

the 2nd approach is a little more flexi here, as regardless of the what the user types (this being quit, qUit, EXIT, exIT) the program will convert this to lower case and match within the condition specified

Sign up to request clarification or add additional context in comments.

Comments

2

Just use the || operator if you want to do more than one check in an if statement:

if (userText.equals("Exit") || userText.equals("Quit")) { ... }

As far as your loop "not looping all the time"; I don't see any loop. Have you failed to include it in your post?

5 Comments

Thanks for the info on the Exit and Quit. I'm trying to loop the: String userText = System.console().readLine("Enter some text:");
The title of your question is about stopping based on two strings which I've helped you with. You don't have a loop in your program so there's no way to help with that part. @ericrk00
@MaciejCygan, I don't trouble myself pondering such things :)
@ChiefTwoPencils still one should not downvote if the answer is correct - trolls :(
As you can tell, I'm new to Java and also to Stack. Thanks for the input.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.