question about while loops
How can I make a while loop only loop once and then ask for user input again? Right now, my while loop goes on forever, but I want it to loop one time, then ask for user input.
Make it take input each time in the loop, not only once like what you are telling the program to do!
Remember, variable names only get their values once, all new values must be done through assignment, so like this:
String yandn = ...; while(yandn.equals("y")) { // more code here yandn = scan.nextLine(); }
try moving String yandn = scan.nextLine();
to the beginning of the while
statement
@MatthewWesolows what do you mean at the beginning of the while statement. like this?: while(String yandn = scan.nextLine()(yandn.equals("y")))
if it's not this, can you show me what it is supposed to look like?
while(yandn.equals("y")) { String yandn = scan.nextLine(); ... }
Let me know if this doesn't work :).
@MatthewWesolows
you deserve stars too * * * *
well if you wanted it to go once you could change the
yandn
variable to""
as the first thing in the while loop. Then if you want it to repeat then have it ask and then makeyandn
equal toscan.nextLine()
then it will repeat the while loopP.S. I've literally never done Java, I'm just using what I know from python, C# and looking at you code, so could be wrong, but I think it should work.
I just forked you repl and tested that out, it worked.
@cuber1515 i dont understand. can you show me?
@xMisbahx sure. So this is what you
while loop
should look like:You'll notice the only difference is the top and bottom of the
while loop
. What's happening isyandn
no longer equals "y" so the while loop will not repeat, but at the end it changes it back so that it repeats after the user says to.@cuber1515 thanks! this really helped
you deserve stars * * * * * * *
np, happy to help @xMisbahx