我的循环旨在接收用户输入,并将其添加到自身中,直到达到给定的最大用户数为止。因此,如果用户输入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);
}
}
}
}
“如果”对您没有好处。我看不到它可以如何帮助您。因此,您的循环可能很简单:
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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句