user203124124134
user203124124134

Reputation: 25

Do-While Loop not looping - Java

I am having a problem with my java code below. I want the loop to stop when the number "-100" but it stops as soon as you enter any number. I'm just learning how to use java so there could be plenty of mistakes here.

    public static void main(String[] args){

        Scanner keyboard = new Scanner (System.in);
                
                String num = "";   

                       do {
                    
            System.out.println("Enter a number: ");

                    int n = keyboard.nextInt();

            System.out.println("The number you entered is: " +n);
                        
            System.out.println("------------------------");
                                                                     
                       } while ("-100".equals(num)); 

    } 
        
} 

Upvotes: 1

Views: 101

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201409

num is always the empty string, because you never change the value of num. You update n. Which is what I would base the loop on. Like,

Scanner keyboard = new Scanner(System.in);
int n;
do {
    System.out.println("Enter a number: ");
    n = keyboard.nextInt();
    System.out.println("The number you entered is: " + n);
    System.out.println("------------------------");
} while (n != -100);

That is, do loop while n is not -100.

Upvotes: 3

Related Questions