Java矩形计算程序:switch触发default时如何实现输入重试循环?
如何实现输入无效时循环重新选择矩形的面积/周长计算
你的问题出在没有把输入逻辑放到循环体内,之前尝试的布尔变量只初始化了一次,没有在每次输入后更新值,导致循环条件一直成立,陷入无限循环。
这里用do-while循环最合适,它能保证输入逻辑至少执行一次,每次输入后检查是否有效,无效就重新提示输入,直到用户输入'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; 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); // 输入无效时提示,有效则进入switch处理 if (choice != 'A' && choice != 'P') { System.out.println("Invalid input. Please enter 'A' or 'P' (Without quotes)."); } } while (choice != 'A' && choice != 'P'); // 循环条件:输入无效就继续循环 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."); } 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))); } } } }
关键修改点说明:
- 用
do-while包裹输入逻辑,确保第一次输入一定会执行,之后每次输入后判断是否有效 - 每次循环都会重新获取用户输入的
choice,更新变量值,避免之前的无限循环问题 - 把无效输入的提示移到循环内,输入无效时直接提示,直到输入正确才退出循环进入计算逻辑
- 原switch的case块里的
break可以去掉,因为Java 14+的箭头语法->会自动隔离每个case块,无需break终止
内容的提问来源于stack exchange,提问作者Jeramiah Sanchez
相关产品推荐
相关产品推荐

