Skip to content
← Back to Community
question about while loops
Profile icon
xMisbahx

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.

Answered by cuber1515 [earned 5 cycles]
View Answer
Voters
Profile icon
xMisbahx
Comments
hotnewtop
Profile icon
cuber1515

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 make yandn equal to scan.nextLine() then it will repeat the while loop

P.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.

Profile icon
cuber1515

I just forked you repl and tested that out, it worked.

Profile icon
xMisbahx

@cuber1515
i dont understand. can you show me?

Profile icon
cuber1515

@xMisbahx
sure. So this is what you while loop should look like:

while(yandn.equals("y")) { yandn = ""; Simon.add("hello"); Simon.add("helloooooo"); Simon.add("there"); Simon.add("how"); Simon.add("are"); Simon.add("you"); Simon.add("good"); Simon.add("bye"); Simon.add("i am"); Simon.add("leaving"); Simon.add("now"); Simon.add("bye"); Random S = new Random(); System.out.println(Simon.get(S.nextInt(Simon.size()))); System.out.println("Simon Says: would you like to continue?"); System.out.println("y or n"); yandn = scan.nextLine(); }

You'll notice the only difference is the top and bottom of the while loop. What's happening is yandn 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.

Profile icon
xMisbahx

@cuber1515
thanks! this really helped
you deserve stars * * * * * * *

Profile icon
cuber1515

np, happy to help

@xMisbahx

Profile icon
Coder100

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(); }
Profile icon
xMisbahx

@Coder100
thanks!

Profile icon
MatthewWesolows

try moving String yandn = scan.nextLine(); to the beginning of the while statement

Profile icon
xMisbahx

@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?

Profile icon
MatthewWesolows

@xMisbahx

while(yandn.equals("y")) { String yandn = scan.nextLine(); ... }

Let me know if this doesn't work :).

Profile icon
xMisbahx

@MatthewWesolows

you deserve stars too * * * *