Ooi Eugene
Ooi Eugene

Reputation: 23

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

Upvotes: 0

Views: 150

Answers (1)

abhijit gupta
abhijit gupta

Reputation: 196

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

Upvotes: 1

Related Questions