【问题标题】:Is there anyway to shorten this Java code?反正有没有缩短这个Java代码?
【发布时间】:2020-10-11 05:04:24
【问题描述】:

有什么方法可以一次性验证身高和体重吗? 有什么方法可以测试
input.hasNextDouble() and height > 5 && height <= 500
if 条件下一起?

    do {
            System.out.print("Height(cm): ");
            input.nextLine();
    
            if (input.hasNextDouble()) {
                height = input.nextDouble();
                if (height > 5 && height <= 500) {
                    isValid = true;
                } else {
                    System.out.println("Invalid input\nPlease try again\n");
                    isValid = false;
                }
            } else {
                System.out.println("Invalid input\nPlease try again\n");
                isValid = false;
            }
        } while (!(isValid));
    
        do {
            System.out.print("Weight(kg): ");
            input.nextLine();
    
            if (input.hasNextDouble()) {
                weight = input.nextDouble();
                if (weight > 0 && weight <= 500) {
                    isValid = true;
                } else {
                    System.out.println("Invalid input\nPlease try again\n");
                    isValid = false;
                }
            } else {
                System.out.println("Invalid input\nPlease try again\n");
                isValid = false;
            }
        } while (!(isValid));

【问题讨论】:

  • 嗯,显而易见的想法是将通用代码重构为可以共享的单个方法。
  • 这样的代码带来的好处是您可以提供有用的错误消息。例如“无效高度:必须在 5 到 500 之间。”

标签: java


【解决方案1】:

将通用代码定义为单个函数并使用三元运算符内联if条件。

    public static double takeInput(String heightOrWeight, int lowConstraint, int highConstraint) {
        Scanner input = new Scanner(System.in);
        double validDouble = 0;
        boolean isValid = false;
        
        while(!(isValid)){
            System.out.print(heightOrWeight + ": ");
            input.nextLine();

            validDouble = input.hasNextDouble() ? input.nextDouble(): Integer.MIN_VALUE;
            
            if (validDouble > lowConstraint && validDouble <= highConstraint) {
                isValid = true;
            }
         
            if (!isValid) {
                 System.out.println("Invalid input\nPlease try again\n");
            }
        }
        return validDouble;
    }

使用适当的参数调用上述方法。

        double height = takeInput("Height(cm)", 5,500);
        double weight = takeInput("Weight(kg)", 0,500);

【讨论】:

  • validDouble = input.hasNextDouble() 是什么? input.nextDouble(): -1;是什么意思?
  • 它是一个三元运算符。 variable x = (expression) ? value if true: value if false 代替 -1,您可以输入任何 Integer.MIN_VALUE 或其他一些不在该范围内的数字
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多