我的循环旨在获取用户输入,并将该号码添加到自身上,直到它到达给定的最大数字为止。因此,如果用户输入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);
}
}
}
}
'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;
只需移动答案=答案 countby从循环的开始到结束
while (answer < maxNum)
{
if (answer > maxNum)
{
System.out.println(answer - countBy);
}
else System.out.println(answer);
answer = answer + countBy;
}
与 @qull @lote
相同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
}
您的循环状况已经确保您不会超越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;
}