0

Basically, what I want my code to do is if the user inputs anything besides "sum, quit, max, min" I want the program to loop back and ask the user the options again. I tried using a while-loop but I can't add multiple String objects within it. I'm stuck on what to do. (Also, I used if-statements instead of while so it won't continually repeat and be stuck.)

EDIT: thank you for the help! I used a while(true), break statements, and a continue at the end and it seems to work!

public static void main (String [] args){
        System.out.println("Enter the option sum, max, min:");
        Scanner input = new Scanner (System.in);
        user = input.nextLine();
        double [] y = theArray();


        if (user.equals("sum")){
            //do something

        }
        else if (user.equals("max")){
            //do something 
        }
        else if (user.equals("min")){
            //do something
        }
        else if (user.equals("Quit")){
            //do something
        }


    }
} 

2 Answers2

1

As I have said in the comment above, use the while infinite loop and break it when the condition is met. If the condition is not met, the loop goes for the next iteration. Keep aware what should be looped and why.

System.out.println("Enter the option sum, max, min:");
Scanner scanner = new Scanner(System.in);
String option;

while (scanner.hasNextLine()) {
    System.out.println("Enter the option sum, max, min:");
    option = scanner.nextLine();
    if ("sum".equals(option)) {
        System.out.println("Sum entered, loop ended");
        // do something
        break;
    } else if ("max".equals(option)) { // the same goes for min, max, quit }
}
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
0

I would suggest using recursion:

public static void main (String [] args){

        Scanner input = new Scanner (System.in);

        promptUser(input);

        System.out.println("done");

    }
    public static void promptUser(Scanner input) {
        System.out.println("Enter the option sum, max, min:");
        String user = input.nextLine();
        double [] y = theArray();


        if (user.equals("sum")){
            //do something
        }
        else if (user.equals("max")){
            //do something
        }
        else if (user.equals("min")){
            //do something
        }
        else if (user.equals("Quit")){
            //do something
        }else {
            //if wrong input is entered, try again
            promptUser(input);
        }
    }
Cardinal System
  • 2,749
  • 3
  • 21
  • 42