简体   繁体   中英

Homework assignment using loops to count (Java)

The assignment is...

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

This is what I have:

  int userNum = 0;
  int i = 0;

  userNum = 4;     // Assume positive

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

  System.out.println("");

I keep getting an infinite loop error. Any help is greatly appreciated. I am new to Java and still trying to figure it out.

Change

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

to something like (since you want 1 to userNum , or 4 in this case)

while (i < userNum) {
    System.out.printf("%d ", ++i); // <-- since you want to start at 1.
}

as is you reset i to the initial value minus 1 on every iteration (thus an infinite loop).

So the issue is the way you are handling i. Please see code below.

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

You should use i++

while (i < userNum) {
     i++;
     System.out.print(i + " ");
  }

Please try the code below, I believe this would resolve your issue.

    int i = 0;
    int userNum = 4;
    while (i < userNum) {
    i++; //keep incrementing i till its less than userNum
    System.out.print(i + " "); //keep printing i till its less than userNum
    }
//come out of the loop when i becomes greater than userNum

you are decrements before print first i=0 condition check i < 4 is true then i=i-1 which is equal to -1 and print again i<4 again decrements i was -1 now -2 so that's why you are getting infinite loop

System.out.println(i + " "); 
i++;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM