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.

New contributor

Jeramiah Sanchez is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

3

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.

You can run a infinite loop. If user input a valid input then you can return/break the loop. Here is the code example.

import java.util.Scanner;

public class Switch_Statement_Practice {


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

       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.");
           choice = scnr.next().charAt(0);

           switch (choice) {
               case 'A' -> {
                   System.out.println("We are going to calculate the area.");
                   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.");
                   return;
               }
               case 'P' -> {
                   System.out.println("We are going to calculate the perimeter.");
                   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)) + " units.");
                   return;
               }
               default -> {
                   System.out.println("Invalid input. Please enter 'A' or 'P' (Without quotes).");
               }
           }
       }
   }
}

Other answers should help you – but I thought I’d suggest the do-while structure for this type of “prompt and process” logic.

In short

boolean invalidInput;

do {
   
    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);

    invalidInput = false;
    
    switch (choice) {
        case 'A' -> {
            // 'A' processing
            break;
        }
        case 'P' -> {
            // 'P' processing
            break;
        }
        default -> {
            // Error processing
            invalidInput = true;
            break;
        }
    }
} while (invalidInput);

// continue with program or 'return'.

Thank you everyone for your answers. David’s answer guided me to the solution I was looking for. As a beginner programmer, everyone’s answers provided valuable insight into new methods I need to learn. My new code is as follows:

public class Switch_Test {

private static char getCalculationOption (Scanner scnr) { // This method contains the desired looping logic and will return the appropriate 'choice' value.
    System.out.println("This program will calculate either the area or perimeter of a rectangle.");
    System.out.println();
    char choice = ' '; // Variable 'choice' has been initialized with value (' ').
    while (choice != 'A' && choice != 'P') { //Since the choice variable has value (' ') and that value isn't 'A' or 'P', this loop will execute.
        System.out.println("Please enter 'A' or 'P' (without quotes) to calculate either the area or perimeter.");
        choice = scnr.next().charAt(0);
    }
    return choice; //Once the user enters a valid input, the choice variable recieves the appropriate 'A' or 'P' character `value and the loop terminates.
}

public static void main(String[] args) { // Main logic.
    Scanner scnr = new Scanner(System.in);
    int height;
    int width;
    char choice;
    
    choice = getCalculationOption(scnr); // The returned 'choice' value from the above method is called.
    
    switch (choice) {
        case 'A' -> {
            System.out.println("We will calculate the area of a rectangle.");
            System.out.println();
            System.out.println("Please enter the height of the rectangle.");
            height = scnr.nextInt();
            System.out.println("Please enter the width of the rectangle.");
            width = scnr.nextInt();
            System.out.println("The area of the rectangle is: " + (height * width) + " units.");
            break;
        }
        case 'P' -> {
            System.out.println("We will calculate the perimeter of a rectangle.");
            System.out.println();
            System.out.println("Please enter the height of the rectangle.");
            height = scnr.nextInt();
            System.out.println("Please enter the width of the rectangle.");
            width = scnr.nextInt();
            System.out.println("The perimeter of the rectangle is: " + ((2 * height) + (2 * width)));
        }
    }
}

}

New contributor

Jeramiah Sanchez is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật