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

时间:2019-03-15 20:55:28

标签: java

我的循环旨在接收用户输入,并将其添加到自身中,直到达到给定的最大用户数为止。因此,如果用户输入27进行计数,并以4000作为最大数,则程序将27加27,并打印出每个结果,直到达到4000。如果最后一个循环将导致程序打印出超出最大数的数(4000之前的27的最后一次迭代是3996,我的程序将打印出4023,即3996 +27。)比我希望它只打印出不超过最大值的最后一个数字大,所以3996。但是,如果它精确地以最大数字结尾,比如说以5计数直到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);
          }
      }
  }
}

4 个答案:

答案 0 :(得分:0)

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

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

              answer = answer + countBy;
      }

答案 1 :(得分:0)

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

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
}

答案 2 :(得分:0)

“如果”对您没有好处。我看不到它可以如何帮助您。因此,您的循环可能很简单:

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;

答案 3 :(得分:0)

您的循环条件已经确保您不会超过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;
}
相关问题