我怎么打印这个循环

时间:2016-04-25 20:33:46

标签: java loops

我希望java问用户需要他的体重或身高都高于0

                    System.out.print("\tEnter your weight in Kilogram: ");
                    double weight = in.nextDouble();

                    System.out.print("\tEnter your height in Centimeter: ");
                    double height = in.nextDouble();

                    if (weight <= 0 || height <= 0) {

                        while (true) {
    System.out.println("Wrong entry for weight or height... try again");
                        }

                    }

                    String clinic = "NUTRITION";

在没有造成无限循环的情况下我无法做到这一点

这是我想要的输出:

    System.out.println("Enter the name (first and last): Omar\n"
            + "Enter your national ID number: 9821444\n"
            + "Enter your age: 30\n"
            + "Enter your mobile number (###-###-####): 055-098-1122\n"
            + "Enter your weight in Kilogram: 0\n"
            + "Enter your height in Centimeter: 176\n"
            + "Wrong entry for weight or height... try again\n"
            + "Enter your weight in Kilogram: 77\n"
            + "Enter your height in Centimeter: 0\n"
            + "Wrong entry for weight or height... try again\n"
            + "Enter your weight in Kilogram: 77\n"
            + "Enter your height in Centimeter: -176\n"
            + "Wrong entry for weight or height... try again\n"
            + "Enter your weight in Kilogram: 77\n"
            + "Enter your height in Centimeter: 176");

3 个答案:

答案 0 :(得分:0)

试试这个:

double height = 0;
double weight = 0;

while (weight <= 0 || height <= 0) {

    System.out.print("\tEnter your weight in Kilogram: ");
    weight = in.nextDouble();

    System.out.print("\tEnter your height in Centimeter: ");
    height = in.nextDouble();

   if (weight <= 0 || height <= 0) {
       System.out.println("Wrong entry for weight or height... try again");
   }
}

答案 1 :(得分:0)

将循环扩展到整个输入逻辑:

            do {
                System.out.print("\tEnter your weight in Kilogram: ");
                double weight = in.nextDouble();

                System.out.print("\tEnter your height in Centimeter: ");
                double height = in.nextDouble();

                if (weight <= 0 || height <= 0) {
                    System.out.println("Wrong entry for weight or height... try again");
                }
            } while(weight <= 0 || height <= 0)

答案 2 :(得分:0)

试试这个:

             boolean cont = true;

            while (cont) {
            System.out.print("\tEnter your weight in Kilogram: ");
            double weight = in.nextDouble();

            System.out.print("\tEnter your height in Centimeter: ");
            double height = in.nextDouble();

            if (weight <= 0 || height <= 0) {


        System.out.println("Wrong entry for weight or height... try again");
                }else{
                    cont=false;
                }
            }