Reputation: 36
While trying to make my code easier to read by naming the boolean, I ran into a problem. It does not execute properly as expected and I'm unable to find reason behind it. The following code executes properly.
import java.util.Scanner;
public class While {
public static void main (String [] args){
int count,number;
System.out.println("Please enter the number you want to count upto:");
Scanner userInput = new Scanner(System.in);
number= userInput.nextInt();
count = 1;
while(count<=number)
{
System.out.println(count +" ,");
count++;
}
}
}
But if I change the code and assign name to the boolean statement for while loop, it does not stop and provide totally unexpected result.
import java.util.Scanner;
public class While {
public static void main (String [] args){
int count,number;
System.out.println("Please enter the number you want to count upto:");
Scanner userInput = new Scanner(System.in);
number= userInput.nextInt();
count = 1;
boolean onlyWhen = (count<=number);
while(onlyWhen)
{
System.out.println(count +" ,");
count++;
}
}
}
Sorry for asking a dumb question but I am just curious and looking for the reason for this unexpected outcome.
The code in question is
boolean onlyWhen = (count<=number);
Thank you for your help in advance.
Upvotes: 0
Views: 56
Reputation: 521053
When you assign:
boolean onlyWhen = (count<=number);
you are making this assignment once, before the loop even starts. The value of onlyWhen
is fixed, and will not change unless you reassign it inside the loop:
while (onlyWhen) {
System.out.println(count +" ,");
count++;
onlyWhen = (count<=number);
}
Note that this isn't such nice code, and I would probably prefer what you had originally:
while (count <= number) {
System.out.println(count +" ,");
count++;
}
Upvotes: 4
Reputation: 393781
boolean onlyWhen = (count<=number);
is only evaluated once, so it's either always true (leading to infinite while loop) or always false (leading to the while loop never being executed).
You have to modify it within the loop in order to make it useful:
boolean onlyWhen = (count<=number);
while(onlyWhen)
{
System.out.println(count +" ,");
count++;
onlyWhen = (count<=number);
}
Upvotes: 3