java - 如何使for循环扫描器代码下降一定数量?

标签 java for-loop java.util.scanner

如何使 for 循环扫描器代码下降到设定的数量? 例如,输入 30,然后输入 3,然后向下输入 30、27、24、21 等。

这就是我到目前为止所拥有的。我希望 int y 代表一次删除的数量。

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");
  }
}

最佳答案

x = x - y;放入for循环内。这将使 x 代表当前卡在墙上的瓶子数量,即,在您的示例中,x 每次迭代都会减少 3。

关于java - 如何使for循环扫描器代码下降一定数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14924794/

相关文章:

java - 延迟设置颜色过滤器java

javascript - 看起来很奇怪的 Javascript for 循环

java - 我的扫描仪不断收到错误 "cannot find symbol"

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

java - 为什么 hasNext() 为假,而 hasNextLine() 为真?

java - 多个 InfoWindows Android map V2

java - 无需下载即可读取远程 csv 文件

java - 在Java中,如何在几行而不是一行中初始化数组中的元素?

for-loop - 对列的值逐行求和

r - 如何在循环运行时将for循环内的变量实时打印到控制台?