+ 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.
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 ...
+ 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
+ 2
Thanks, Shruti. When I do that I get no output at all.
+ 2
Ah! Thank you, Gordie! It worked!
+ 1
multiply the orginal line of code by 2
+ 1
if you don't want to print every no. ....
try this:
do{
int s =testnumber*=2;
}while(testnmber<1000000);
System.out.println(s);
+ 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
____________________________