-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.

Luke Garrigan
  • 4,571
  • 1
  • 21
  • 29
Supremo
  • 13
  • 6

3 Answers3

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.

Ben221199
  • 128
  • 2
  • 8
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);
Muska
  • 46
  • 5
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
Luke Garrigan
  • 4,571
  • 1
  • 21
  • 29