2016-04-25 52 views
0

我希望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"); 
+0

相關:http://stackoverflow.com/questions/36845766/how-do-i-simplify -this-integer-validation/36846116#36846116 – Gendarme

+1

這不應該被標記爲「javascript」,因爲這是一個Java問題。 – AmericanUmlaut

回答

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