【问题标题】:How to make loop run as many times as user inputs?如何使循环运行与用户输入一样多次?
【发布时间】:2016-11-14 14:38:38
【问题描述】:

我有一个 for 循环,调用它的方法是 printMe(),我希望用户能够确定它在输入时运行了多少次。这与我认为应该是的一致:

  System.out.println("Enter a number: ");
  loop = input.nextInt();

【问题讨论】:

  • 你搞定了吗?
  • 嗨 Itamar Green,当我尝试集成您的代码时,我得到了无法找到输入符号。
  • Scanner 对象的名称需要与用于调用.nextInt() 的名称相同。
  • 现在没有错误,但是当我输入我希望for循环方法工作的次数时,它仍然只执行一次?
  • 您使用的代码是什么?请编辑您的问题

标签: java loops for-loop


【解决方案1】:

这应该可行:

Scanner input = new Scanner(System.in);
int loop = input.nextInt();
for(int i = 0; i<loop;i++){
    //do the thing
}

【讨论】:

    【解决方案2】:

    借助扫描仪读取用户输入

    Scanner sc = new Scanner(System.in);
    int loopNum = sc.nextInt();
    for (int i=); i<loopNum; i++){
        printMe();
    }
    

    【讨论】:

      【解决方案3】:

      应该是这样的:

      for (int i=0; i<loopNum; i++)
        printMe();
      

      干杯

      【讨论】:

        【解决方案4】:

        是的,如果您的变量输入来自 Scanner 类,则它是正确的。你可以像这样声明变量sc,如果你想从用户那里读取更多的输入,可以多次调用它。

        Scanner sc = new Scanner(System.in); 
        System.out.println("Enter a number: ");
        loopNum = sc.nextInt();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-11-15
          • 2016-09-18
          • 1970-01-01
          • 1970-01-01
          • 2020-04-03
          • 2015-02-10
          相关资源
          最近更新 更多