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.
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)));
}
}
}
}
Jeramiah Sanchez is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.