首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使一个for循环扫描器代码在一定数量下运行?

如何使一个for循环扫描器代码在一定数量下运行?
EN

Stack Overflow用户
提问于 2013-02-18 02:55:49
回答 2查看 409关注 0票数 0

如何使一个for循环扫描器代码在一定数量下运行?例如,输入30,然后输入3,然后它就像30,27,24,21,等等。

这就是我到目前为止所拥有的。我想让int y表示一次取下的数量。

代码语言:javascript
复制
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");
  }
}
EN

回答 2

Stack Overflow用户

发布于 2013-02-18 03:06:49

x = x - y;放入for循环中。这将使x表示当前挂在墙上的瓶子的数量,也就是说,x将在每次迭代时递减3。

票数 1
EN

Stack Overflow用户

发布于 2013-02-18 03:13:14

将for循环替换为:

代码语言:javascript
复制
for (int counter = x; counter > 0; counter-=y)

这将为您提供所需的输出。

counter-=y更改等同于counter=counter-y

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14924794

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档