代码之家  ›  专栏  ›  技术社区  ›  Stephanie

Do While语句卡在无限循环中

  •  -2
  • Stephanie  · 技术社区  · 7 年前

    你未来的孩子最适合长到4英尺10英寸。 你未来的孩子最适合长到4英尺10英寸。 你未来的孩子最适合长到4英尺10英寸。 你未来的孩子最适合长到4英尺10英寸。 你未来的孩子最适合长到4英尺10英寸。 你未来的孩子最适合长到4英尺10英寸。 你未来的孩子最适合长到4英尺10英寸。 你未来的孩子最适合长到4英尺10英寸。 你未来的孩子最适合长到4英尺10英寸。 你未来的孩子最适合长到4英尺10英寸

    //允许使用键盘 扫描仪键盘输入=新扫描仪(系统输入);

        //Allows user to input numbers
        System.out.println("Enter the gender of your future child. Use 1 for Female and 0 for Male: ");
        int Gender = keyboardInput.nextInt();
        System.out.println("Enter the height in feet, then in inches of the mom: ");
        int MomHeight = keyboardInput.nextInt();
        System.out.println("Enter the height in feet, then the height in inches of the dad: ");
        int DadHeight = keyboardInput.nextInt();
    
        int female;
        int male;
        int HeightFeet;
        int HeightInches;
    
        DecimalFormat feet = new DecimalFormat("#0");
        DecimalFormat inches = new DecimalFormat("#0");
    
        //Loop statements
        while (Gender == 0)
        {
           male = (MomHeight * 13 / 12 + DadHeight) / 2;
           HeightFeet = male / 12;
           HeightInches = male % 12;   
    
        System.out.print("Your future child is estimated to grow to " + feet.format(HeightFeet));
        System.out.print(" feet and " + inches.format(HeightInches));
        System.out.print(" inches.");
        System.out.println("");
        }
    
        while (Gender == 1)
        {
            female = (DadHeight * 12 /13 + MomHeight) /2;
            HeightFeet = female / 12;
             HeightInches= female % 12;
    
        System.out.print("Your future child is estmated to grow to " + feet.format(HeightFeet));
        System.out.print(" feet and " + inches.format(HeightInches));
        System.out.print(" inches.");
        System.out.println("");
        } } }
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   davidxxx    7 年前

    在你的循环中, Gender 从不修改。所以你真的永远在循环。
    while 陈述
    if else if

    顺便说一下,您应该命名变量 gender 而不是 要遵守Java命名约定:

    if (gender == 0){
          ...
    }
    
    else if (gender == 1){
           ...
    }
    

    如果要多次重复所有处理,可以使用循环:

     boolean again = false;
     do{
           if (gender == 0){
              ...
           }
    
           else if (gender == 1){
               ...
           }
           ...
          again = keyboardInput.nextBoolean();
    
     } while (again);
    
        2
  •  0
  •   Mohit Mandokhot    7 年前

    为了退出循环,您需要在循环在您所需的次数之后执行之后,条件变为false。

    while (Gender == 0){
    //Do this
    }
    
    while (Gender == 1){
    //Do this instead
    }
    

    因此,做出选择是基于 性别

    //Assume print is to be done 2 times
    
    int count = 1;
    
    if(Gender == 0){
    //Female selection
    while( count < 3 ){
     // Execute female code
     count++;
    }
    else if(Gender == 1){
    //Male selection
    while( count < 3 ){
     // Execute male code
     count++;
    }