Search code examples
javawhile-loopdo-whilemultiplication

how do i repeatedly multiply a number in java by 2 until it reaches 1 million?


import java.util.Scanner;

class Main {

    static Scanner userInput = new Scanner(System.in);

    public static void main(String[] args) {
        int testNumber = userInput.nextInt();
        do{
             System.out.println(newNumber * 2);
             newNumber++;
        }while( testNumber < 1000000);
    }
}

Solution

  • You have the right idea with your loop, but you have multiple problems with your variables.

    1. Your first problem is that you read in a variable from the user - testNumber, but then you are (incorrectly) manipulating a completely different variable - newNumber.
    2. Your second problem is that you are testing the unchanged variable as your stop condition.

    You probably want your loop to be something like:

        do {
             testNumber = testNumber * 2;
             System.out.println(testNumber);
        } while(testNumber < 1000000);