简体   繁体   中英

How can I get the loop to work in my Java program?

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?

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.

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