我在课堂作业中做了一个 switch 语句,它将根据用户的输入计算矩形的面积或周长,我想这样做,以便如果用户输入无效的输入,程序将循环回到首先要求用户输入“A”或“P”进行相应的计算。
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).");
}
}
}
我尝试声明
boolean invalidInput;
并声明 invalidInput = choice != 'A' && choice != 'P';
,并在要求用户重新输入选择的地方进行 while(invalidInput) {System.out.println("Invalid input. Please enter 'A' or 'P'"); choice = scnr.nextLine().charAt(0);}
循环,但我进入了无限循环。
您可以运行无限循环。如果用户输入有效的输入,那么您可以返回/中断循环。这是代码示例。
导入java.util.Scanner;
公共类 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).");
}
}
}
}
}