Ask coding questions

← Back to all posts
question about while loops
h
xMisbahx (6)

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 (90) [earned 5 cycles]
View Answer
Comments
hotnewtop
cuber1515 (90)

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.

cuber1515 (90)

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

xMisbahx (6)

@cuber1515 i dont understand. can you show me?

cuber1515 (90)

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

xMisbahx (6)

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

Coder100 (18818)

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();
}
MatthewWesolows (35)

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

xMisbahx (6)

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

MatthewWesolows (35)

@xMisbahx

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

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

xMisbahx (6)

@MatthewWesolows
you deserve stars too * * * *