如何使for循环扫描程序代码以一定数量的数量下降? 例如,输入30,然后输入3,然后输入30,27,24,21等。
这是我到目前为止所拥有的。我想要表示一次取下多少。
import java.util.Scanner; // ...
public class b
{
public static void main(String[] args) {
int x,y;
Scanner scannerObject = new Scanner(System.in);
System.out.println("how many bottles hanging on the wall");
x = scannerObject.nextInt();
System.out.println("how many bottles are taken down the wall");
y = scannerObject.nextInt();
for (int counter = x; counter > 0; counter--)
{
if (counter == 1)
{
System.out.println(" " + counter + " bottle hanging on the wall");
}
else
{
System.out.println(" " + counter + " bottles hanging on the wall");
}
System.out.println("And if one bottle should accidently fall, ");
}
System.out.println("No bottles hanging on the wall");
}
}
答案 0 :(得分:1)
将x = x - y;
放入for循环中。这将使x
代表当前挂在墙上的瓶子数量,即,x
将在每次迭代时减少3个给定的例子。
答案 1 :(得分:1)
将for循环替换为:
for (int counter = x; counter > 0; counter-=y)
这应该会给你想要的输出。
counter-=y
更改相当于counter=counter-y