+ 3

Not quite understanding the do while loop.

Instructions from the teacher - Using a do-while loop, multiply the given number variable by two until its value is over 1 million. In each iteration of the loop, after you multiply the number variable. Here's my code: import java.util.Scanner; class Main { static Scanner userInput = new Scanner(System.in); public static void main(String[] args) { int testNumber = userInput.nextInt(); // Write your code below here do { System.out.println(testNumber*2); testNumber++; } while(testNumber == 1000000); } } My output is 10. I like this but how do I get it to loop through and times them all by 2 each loop? Thanks.

25th Oct 2018, 4:05 PM
Kiowa Alumno
Kiowa Alumno - avatar
8 Antworten
+ 4
do while first evaluate and then check the condition. it means loop can run at least one time .change the condition while(testNumber<1000000) I think it can help you , if no let me know ...
25th Oct 2018, 5:00 PM
Shruti
Shruti - avatar
+ 4
It probably times out because you want it to count to 1 million and print a million lines of output. If you reduce it to while(... <= 500) it should work better
25th Oct 2018, 5:23 PM
Anna
Anna - avatar
+ 2
Thanks, Shruti. When I do that I get no output at all.
25th Oct 2018, 5:12 PM
Kiowa Alumno
Kiowa Alumno - avatar
+ 2
Ah! Thank you, Gordie! It worked!
25th Oct 2018, 5:51 PM
Kiowa Alumno
Kiowa Alumno - avatar
+ 1
multiply the orginal line of code by 2
26th Oct 2018, 12:39 PM
4N0NYM0U5
4N0NYM0U5 - avatar
+ 1
if you don't want to print every no. .... try this: do{ int s =testnumber*=2; }while(testnmber<1000000); System.out.println(s);
27th Oct 2018, 4:00 AM
Shruti
Shruti - avatar
+ 1
____________________________ the do while statement really helps when youre trying to increment something. my example i'snt written in actual code but it gives you an idea of whats happening: var: numberOfApples NumberOfApples=0 do{ inc. NumberOfApples } while NumberOfApples<10 hope this helped😎 zach ____________________________
27th Oct 2018, 4:21 AM
Zach N.
Zach N. - avatar