java - 使用循环计数的作业分配(Java)

标签 java oop while-loop

任务是...

Write a while loop that prints 1 to userNum, using the variable i. Follow each number (even the last one) by a space. Assume userNum is positive. Ex: userNum = 4 prints: 1 2 3 4

这是我的:

  int userNum = 0;
  int i = 0;

  userNum = 4;     // Assume positive

  while (i < 4) {
     i = userNum - 1;
     System.out.print(userNum + " ");
  }

  System.out.println("");

我一直收到无限循环错误。任何帮助是极大的赞赏。我是 Java 的新手,仍在努力弄明白。

最佳答案

所以问题是你处理 i 的方式。请看下面的代码。

int userNum = 0;
int i = 0;

userNum = 4;     // Assume positive

while (i < 4) {
   //i = userNum - 1; // this line will result in i equals 4 minus 1 which equal 3 infinitely
   i++; // this means after each iteration of the this line add 1 to i
   System.out.print(i + " ");
}

System.out.println("");

关于java - 使用循环计数的作业分配(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39432641/

相关文章:

java - Getter 和 Setter 函数帮助和操作方法

PHP5 : Callbacks between Class Objects

python - 基于 YAML 数据的条件 Python for 循环

java - ModelMapper 映射错误的 id

java - 如何减少数组的运行时间

java - 无法理解 'Effective Java' 中关于 compareTo 的摘录

javascript - 基本 While 循环查询 - 为什么记录 "1"?

Java While循环不会循环

java - 在参数化查询中使用加号连接字符串

c++ - 虚拟成员类的调用方法