You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过JOptionPane实现符合指定可选值的aNbrTanks输入验证

问题解决:限定燃油箱数量输入为指定值

需求:燃油箱数量aNbrTanks的取值只能是(2,4,8,10,15,20),通过JOptionPane获取输入,若输入不符合规则则重新询问。此前尝试用数组限定输入时出现Object cannot be converted to int或int[] to int的类型转换错误。

实现思路

  • 使用Set<Integer>存储允许的数值,相比数组更高效判断输入值是否合法
  • 循环获取输入,同时处理非数字输入和不在允许范围内两种错误情况
  • 不符合要求时,弹出提示框告知合法取值范围,重新获取输入

修改后的完整代码

package project2;
import javax.swing.JOptionPane;
import java.util.HashSet;
import java.util.Set;

public class VehicleApp {
    public static void main(String[] args) {
        // 姓名输入逻辑
        String firstName = JOptionPane.showInputDialog("Please enter your first name");
        while(firstName.equals("")){
           firstName = JOptionPane.showInputDialog("Please enter a valid first name");
        }
        String lastName = JOptionPane.showInputDialog("Please enter your last name");
        while(lastName.equals("")){
            lastName = JOptionPane.showInputDialog("Please enter a valid last name");
        }
        String aName = firstName + " " + lastName;
        
        // 电话输入逻辑
        String aphone = JOptionPane.showInputDialog("Please enter your number");
        while(aphone.length()!=10){
            aphone = JOptionPane.showInputDialog("Please enter a valid phone number");
        }
        String aPhone = ("" + aphone).replaceAll("(...)(...)(....)", "$1-$2-$3");
        
        // 车辆数量输入逻辑
        int aNbrVehicles = 0;
        boolean validVehicleCount = false;
        while(!validVehicleCount){
            try {
                aNbrVehicles = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Vehicles"));
                if(aNbrVehicles >=1 && aNbrVehicles <=10){
                    validVehicleCount = true;
                } else {
                    JOptionPane.showInputDialog("Valid number of Vehicles (1-10)");
                }
            } catch(NumberFormatException e){
                JOptionPane.showInputDialog("Please enter a valid integer for vehicle count");
            }
        }
        
        // 燃油箱数量输入逻辑(核心修改部分)
        int aNbrTanks = 0;
        boolean validTankCount = false;
        // 定义允许的燃油箱数值集合
        Set<Integer> allowedTanks = new HashSet<>();
        allowedTanks.add(2);
        allowedTanks.add(4);
        allowedTanks.add(8);
        allowedTanks.add(10);
        allowedTanks.add(15);
        allowedTanks.add(20);
        
        while(!validTankCount){
            try {
                String input = JOptionPane.showInputDialog("Enter the number of Tanks (allowed values: 2,4,8,10,15,20)");
                aNbrTanks = Integer.parseInt(input);
                if(allowedTanks.contains(aNbrTanks)){
                    validTankCount = true;
                } else {
                    JOptionPane.showMessageDialog(null, "Invalid tank count. Allowed values are: 2,4,8,10,15,20");
                }
            } catch(NumberFormatException e){
                JOptionPane.showMessageDialog(null, "Please enter a valid integer for tank count");
            }
        }
        
        VehicleFactory JarApp = new VehicleFactory(aName, aPhone, aNbrVehicles, aNbrTanks);
       
        JarApp.calcManufacturingCost();
        JarApp.calcFuelTankCost();
        JarApp.calcSubtotal();
        JarApp.calcTax();
        JarApp.calcTotal();
        JOptionPane.showMessageDialog(null, JarApp.getSummary());
    }
}

关键说明

  1. 集合存储合法值:用HashSet存储允许的数值,调用contains()方法即可快速判断输入是否合法,避免数组遍历的麻烦
  2. 异常处理:捕获NumberFormatException,处理用户输入非数字的情况,防止程序崩溃
  3. 循环校验:通过布尔变量控制循环,直到输入符合要求才退出循环

内容的提问来源于stack exchange,提问作者Jared Castaneda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 23:50:36