简体   繁体   中英

Is there anyway to shorten this Java code?

Is there any way to validate height and weight in one do while? Is there any way to test
input.hasNextDouble() and height > 5 && height <= 500
together on an if condition?

    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));

Defining a common code into a single function and Using ternary operator to inline if condition.

    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;
    }

Calling above method with appropriate parameters.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM