Jave while循环

时间:2019-02-23 23:25:28

标签: java

Java的初学者。使用Zybooks。对我来说,该软件的教学效果不佳,含糊不清。 这是问题:

给定正整数numInsects,编写一个while循环,将输出的数字加倍而不达到200。在每个数字后跟一个空格。循环后,打印换行符。例如:如果numInsects = 16,则打印:

16 32 64 128

这是我所拥有的:

import java.util.Scanner;

public class InsectGrowth {
   public static void main (String [] args) {
      int numInsects;
      Scanner scnr = new Scanner(System.in);
      numInsects = scnr.nextInt(); // Must be >= 1

       System.out.print(numInsects + " ");

  while (numInsects <= 100) {
     numInsects = numInsects * 2;
     System.out.print(numInsects + " ");
  }

  System.out.println();

   }
}

结果是:它没有通过200,只是留下了空白。 用16.测试 您的输出 16 32 64 128 用98测试。 您的输出 98196 用200测试。 输出有所不同。请参阅下面的重点内容。 您的输出 200 预期产量

5 个答案:

答案 0 :(得分:0)

这是处理极端情况的问题。如您所见,您的while循环超出边界条件一遍。因此,您只需要调整条件即可。

使用以下代码块

替换您的while循环:

使用

     if(numInsects <= 200) {
         System.out.print(numInsects);
     }
     while (numInsects <= 100) {
         numInsects = numInsects * 2;
         System.out.print(" " + numInsects);
     }

答案 1 :(得分:0)

将您的第一张照片移至while循环中,并检查200

public class InsectGrowth {
   public static void main (String [] args) {
      int numInsects;
      Scanner scnr = new Scanner(System.in);
      numInsects = scnr.nextInt(); // Must be >= 1

      while (numInsects < 200) {
          System.out.print(numInsects + " ");
         numInsects = numInsects * 2;
      }

      System.out.println();

   }
}

答案 2 :(得分:0)

您的while循环看到的是numInsects的当前值,而不考虑实际应用的是什么。

示例:

import java.util.Scanner;

public class ex {

    public static void main(String[] args) {
        int numInsects;
        Scanner scnr = new Scanner(System.in);
        numInsects = scnr.nextInt(); // Must be >= 1

        System.out.print(numInsects + " ");
        /*
          is  16 less than 200? yes
          is  32  less than 200? yes
          is  64 less than 200? yes
          is  128 less than 200? yes
          is  256 less than 200? no, break

          but if
          is  16 *2  less than 200? yes
          is  32  *2  less than 200? yes
          is  64 *2  less than 200? yes
          is  128  *2 less than 200? no, break
        */

        while (numInsects * 2 < 200) {
            numInsects = numInsects * 2;
            System.out.print(numInsects + " ");
        }

        System.out.println();

    }
}

答案 3 :(得分:0)

您的numInsects将始终为0,您应该说int numInsects = 1;  因为您正在这样做:

0 * 2 = 0 0 * 2 = 0 0 0 0 0 0

答案 4 :(得分:-1)

while (true) {
   numInsects = numInsects * 2;
   if (numInsects >= 200) break;
   System.out.print(numInsects + " ");
}

为了突出显示这种方式,这对您来说更清晰,而且自学习以来,您可以有多种吃鱼的方式,了解您会遇到每个人都以不同的方式来做是一件好事。