Home > front end >  Looping a switch/case statement when user inputs the wrong input
Looping a switch/case statement when user inputs the wrong input

Time:05-06

I would like the user to have another chance at entering the right option instead of the whole code to crash.

public static void main(String[] args) throws java.io.FileNotFoundException {
    int select = getSelection();
    switch(select){
        case 1:
            substringProblem();
            break;
        case 2:
            pointsProblem();
            break;
        case 3:
            System.out.println("Goodbye!");
            System.exit(0);
            break;
        default: 
            System.out.println("Invalid option. Try again");
            getSelection();
            break;
    }
}

CodePudding user response:

This code will do the task for you:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;

public class Test {

    public static void main(String[] args) {
        boolean wrongInput = true;
        Scanner scan = new Scanner(System.in);
        int select;
        System.out.println("Print the select number");
        while(wrongInput) {
            select = getSelection(scan);
            switch(select){
                case 1:
                    substringProblem();
                    wrongInput = false;
                    break;
                case 2:
                    pointsProblem();
                    wrongInput = false;
                    break;
                case 3:
                    System.out.println("Goodbye!");
                    wrongInput = false;
                    System.exit(0);
                    break;
                default: 
                    System.out.println("Invalid option. Try again");
                    wrongInput = true;
                    break;
            }
        }
    }

    private static void pointsProblem() {
        System.out.println("Points problem");
    }

    private static void substringProblem() {
        System.out.println("Substring problem");
    }

    private static int getSelection(Scanner scan) {
        int result = scan.nextInt();
        return result;
    }
}

CodePudding user response:

Could use a while loop and put a verification statement("Are you sure? Y/N:")in each switch statement that loops back to the initial input. Put a boolean variable as the while condition that is triggered by the verification statement. That way it always loops back until you answer y or n to proceed or break the loop.

  • Related