Java .nextLine() repeats line -
everything of guessing game alright, when gets part of asking user if he/she wants play again, repeats question twice. found out if change input method nextline() next(), doesn't repeat question. why that?
here input , output:
i'm guessing number between 1-10 guess? 5 wrong. 3 want play again? (y/n) want play again? (y/n) n
here code:(it in java) last while loop block part asks user if he/she wants play again.
import java.util.scanner; public class guessinggame { public static void main(string[] args) { scanner input = new scanner(system.in); boolean keepplaying = true; system.out.println("welcome guessing game!"); while (keepplaying) { boolean validinput = true; int guess, number; string answer; number = (int) (math.random() * 10) + 1; system.out.println("i'm guessing number between 1-10"); system.out.print("what guess? "); { validinput = true; guess = input.nextint(); if (guess < 1 || guess > 10) { validinput = false; system.out.print("that not valid input, " + "guess again: "); } } while(!validinput); if (guess == number) system.out.println("you guessed correct!"); if (guess != number) system.out.println("you wrong. " + number); { validinput = true; system.out.print("do want play again? (y/n) "); answer = input.nextline(); if (answer.equalsignorecase("y")) keepplaying = true; else if (answer.equalsignorecase("n")) keepplaying = false; else validinput = false; } while (!validinput); } } }
in do while
loop, don't want nextline()
, want next()
.
so change this:
answer = input.nextline();
to this:
answer = input.next();
note, others have suggested, convert while
loop. reason do while
loops used when need execute loop @ least once, don't know how need execute it. whilst it's doable in case, suffice:
system.out.println("do want play again? (y/n) "); answer = input.next(); while (!answer.equalsignorecase("y") && !answer.equalsignorecase("n")) { system.out.println("that not valid input. please enter again"); answer = input.next(); } if (answer.equalsignorecase("n")) keepplaying = false;
the while
loop keeps looping long "y" or "n" (ignoring case) isn't entered. is, loop ends. if
conditional changes keepplaying value if necessary, otherwise nothing happens , outer while
loop executes again (thus restarting program).
edit: explains why original code didn't work
i should add, reason original statement didn't work because of first do while
loop. in it, use:
guess = input.nextint();
this reads number off line, not return of line, meaning when use:
answer = input.nextline();
it detects leftover carriage nextint()
statement. if don't want use solution of reading next()
swallow leftover doing this:
guess = input.nextint(); input.nextline(); rest of code normal...
Comments
Post a Comment