繁体   English   中英

如何防止我的循环两次打印出相同的最后一个数字

[英]How to prevent my loop from printing out the same last number twice

我的循环旨在获取用户输入,并将该数字添加到自身,直到达到给定最大数量的用户。 因此,如果用户输入27进行计数,并以4000作为最大数,则程序将27加27,并打印出每个结果,直到达到4000。如果最后一个循环将导致程序打印出超出最大数的数(4000之前的27的最后一次迭代是3996,我的程序将打印出4023,即3996 +27。)比我希望它只打印出不超过最大值的最后一个数字大,所以3996。但是,如果它正好在最大数字上结束,比如计算到五,直到100,我仍然希望它打印100。只是切掉那个数字以外的任何东西。 知道如何阻止它这样做吗?

import java.util.Scanner;

public class Activity5
{
  public static void main(String[] args)
  {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter number to count by");
    int countBy = keyboard.nextInt();
    System.out.println("Enter maximum number");
    int maxNum = keyboard.nextInt();
    int answer = 0;
    while (answer < maxNum)
      {
        answer = answer + countBy;
          {
              if (answer > maxNum)
              {
                  System.out.println(answer - countBy);
              }
              else System.out.println(answer);
          }
      }
  }
}

只需将答案=答案+计数从循环的开始到结束

 while (answer < maxNum)
      {
              if (answer > maxNum)
              {
                  System.out.println(answer - countBy);
              }
              else System.out.println(answer);

              answer = answer + countBy;
      }

与@СергейКоновалов相同,但只使用一个没有else的if语句

while (answer < maxNum){
    answer = answer + countBy;
    if (answer < maxNum)
    {
        System.out.println(answer);
    }
    //answer = answer + countBy; produces a 0 as the print is run first
}

'if'对你没有好处。 我看不出它对你有什么帮助。 所以你的循环可以像下面这样简单:

public static void main(String ...args) {
    int countBy = 27;
    int maxNum = 200;
    int answer = countBy;
    while (answer < maxNum)
    {
        System.out.println(answer);
        answer = answer + countBy;
    }
}

输出:

27
54
81
108
135
162
189

如果您不想打印初始countBy编号,请将此行更改为:

int answer = 2 * countBy;

您的循环条件已经确保您不会超过maxNum,因此只需

int answer = 0;
while (answer < maxNum) {
    System.out.println(answer);
    answer += countBy;
}

如果你不想要你的例子中的第一个数字,那么

int answer = countBy;
while (answer < maxNum) {
    System.out.println(answer);
    answer += countBy;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM