Search code examples
javaloopsnetbeansswitch-statement

How to loop this switch statement if it defaults?


I went over making a switch statement in my homework for class which will calculate the area or perimeter of a rectangle based on the user's input and I wanted to make it so that if the user enters an invalid input, the program would loop back to the start where it asks the user to enter either 'A' or 'P' for the respective calculation.

import java.util.Scanner;

public class Switch_Statement_Practice {

    //Create a program that calculates the area or perimeter of a rectangle based on user input.
    
    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        int height;
        int width;
        char choice;
        
        System.out.println("Do you want to calculate the area or perimeter of the rectangle? Type 'A' for area or 'P' for perimeter.");
        choice = scnr.next().charAt(0); //.charAt(0) returns the character at the specified index position in a string. 0 returns the first characater in a given string.

        switch (choice) {
            case 'A' -> {
                System.out.println("We are going to calculate the area.");
                System.out.println("");
                System.out.println("Enter the height.");
                height = scnr.nextInt();
                System.out.println("Enter the width");
                width = scnr.nextInt();
                System.out.println("The area is " + height * width + " units.");
                break;
            }
            case 'P' -> {
                System.out.println("We are going to calculate the perimeter.");
                System.out.println("");
                System.out.println("Enter the height.");
                height = scnr.nextInt();
                System.out.println("enter the width.");
                width = scnr.nextInt();
                System.out.println("The perimeter is: " + ((2 * height) + (2 * width)));
                break;
            }
            default -> {
                System.out.println("Invalid input. Please enter 'A' or 'P' (Without quotes).");
            }
        }
    }

I tried declaring boolean invalidInput; and declaring invalidInput = choice != 'A' && choice != 'P';, and making while(invalidInput) {System.out.println("Invalid input. Please enter 'A' or 'P'"); choice = scnr.nextLine().charAt(0);} loop where it asked the user to reenter the choice, but I entered an infinite loop.


Solution

  • It sounds like this is the part you want to loop:

    System.out.println("Do you want to calculate the area or perimeter of the rectangle? Type 'A' for area or 'P' for perimeter.");
    choice = scnr.next().charAt(0); //.charAt(0) returns the character at the specified index position in a string. 0 returns the first characater in a given string.
    

    Though it also sounds like you're confusing that with the switch structure. Rather than get mixed up with the other logic in this method, extract this specific logic to a new method which will contain the loop. For example:

    private static char getCalculationOption(Scanner scnr) {
        System.out.println("Do you want to calculate the area or perimeter of the rectangle? Type 'A' for area or 'P' for perimeter.");
        return scnr.next().charAt(0);
    }
    

    And in your main logic you'd simply call that method:

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        int height;
        int width;
        char choice;
        
        choice = getCalculationOption(scnr);
    
        switch (choice) {
        // etc...
    

    Now within that method simply add your looping logic. For example:

    private static char getCalculationOption(Scanner scnr) {
        while (true) {
            System.out.println("Do you want to calculate the area or perimeter of the rectangle? Type 'A' for area or 'P' for perimeter.");
            char choice = scnr.next().charAt(0);
            if (choice == 'A' || choice == 'P') {
                return choice;
            }
        }
    }
    

    Note that the loop is intentionally infinite and will repeat until control leaves the method through the return statement, which is only invoked if the input is valid.

    Alternatively, if you prefer a controlled condition instead of an infinite loop:

    private static char getCalculationOption(Scanner scnr) {
        char choice = ' ';
        while (choice != 'A' && choice != 'P') {
            System.out.println("Do you want to calculate the area or perimeter of the rectangle? Type 'A' for area or 'P' for perimeter.");
            choice = scnr.next().charAt(0);
        }
        return choice;
    }
    

    In this case choice is initialized to an invalid value and the loop continues until it's been replaced with a valid value, after which the method returns that value.