-1

I have a integer variable but I want it so that if the user inputs the string 'quit' it will close the program.

public static void input() {
    System.out.println("Input: ");
    Integer choice = scan.nextInt();
    choiceExecute(choice);
    if (choice == 'quit') {
        goBack();
    }
}

Thanks in advance.

5
  • Choice is an int so therefore will never be ‘quit’. Also for comparing Strings, use .equals(), not == Commented Dec 10, 2017 at 12:05
  • 'quit' isn't a string, that's a 4-character char literal... which is invalid. Commented Dec 10, 2017 at 12:08
  • Possible duplicate of Difference between "char" and "String" in Java Commented Dec 10, 2017 at 12:25
  • Use System.exit(0) Commented Dec 10, 2017 at 13:32
  • @Ahmad goBack() might not be the same as System.exit(0)... Commented Dec 11, 2017 at 13:17

3 Answers 3

1

Use scan.hasNextInt() to check if the input is a Integer. If so, you can use scan.nextInt(); for getting the integer. If it returns false, you can read the value with scan.nextLine(). If this equals quit, the program should close.

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

Comments

0

There are a couple things wrong here. This only searches for Integers:

Integer choice = scan.nextInt();

However, this will return the entire line:

String line = scan.nextLine();

And from this you can do the check to see if it is equal to quit:

if(line.equals("quit"){
    // do your processing
    goBack();
}else{
    Integer num = Integer.parseInt(line);
    // do your processing on the number
    choiceExecute(num);
}

This is of course making the assumption that you are only storing one item per line and that all other lines that are not equal to "quit" are indeed numbers. Here is how I assume your data looks:

221
357
quit
43
565
quit

Comments

0

One way would be to just read in strings using:

scan.nextLine();

(So you can easily check for "quit").

Then just covert the string to an Integer using:

Integer.parseInt(myString);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.