Reputation: 653
import java.util.Scanner;
import static java.lang.System.out;
public class TestingStuf2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
out.println("Enter a number");
int number = keyboard.nextInt();
while (number < 10) {
if (number < 10) {
out.println("This number is too small.");
keyboard.nextInt();
}else{
out.println("This number is big enough.");
}
}
keyboard.close();
}
}
I'm just having a little trouble looping this code. I've just started to learn Java a these loops have been confusing me the whole time. When I run this program, if I enter a number less than 10 I get the message that says ""This number is too small" and then it allows me to type again. However if I then type a number greater than 10 I get the same message. Also, if the first number I enter is greater than 10, I get no message at all, the program just ends. Why is this happening?
Upvotes: 0
Views: 40
Reputation: 11075
I think you have forgot to reassign the number
variable. That's the reason why
However if I then type a number greater than 10 I get the same message.
Please try the code below. Thanks for @Dev.Joel's comment. I have modified the loop to do-while
to suit the case better.
import java.util.Scanner;
import static java.lang.System.out;
public class TestingStuf2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
out.println("Enter a number");
int number = keyboard.nextInt();
do{
if (number < 10) {
out.println("This number is too small.");
/*
* You should reassign number here
*/
number = keyboard.nextInt();
}else{
out.println("This number is big enough.");
}
}while(number < 10);
keyboard.close();
}
}
I suggest you use break point
to debug your problem. In your case, for example, you assign 2 to number
, and "This number is too small" is printed. Next, you use keyboard.nextInt()
to let user input another int. However, the number is still 2. Thus condition number < 10
is true no matter what you input this time, and "This number is too small"
is printed again.
Upvotes: 3