为什么我的字符串输入被跳过了?

时间:2016-03-05 05:07:25

标签: java while-loop

我一直感到沮丧,因为我的输入由于某种原因被程序跳过。这会导致跳过while循环并停止程序。

    public static void main(String[] args) 
{
    Scanner input = new Scanner(System.in);
    Random random = new Random();

    System.out.println("Guess a number between 1 and 10.");
    int count = 1;
    int guess = input.nextInt();
        int answer = random.nextInt(1) + 1;

    while(guess != answer)
    {
        System.out.println("Wrong answer. Try again.");
        guess = input.nextInt();
        count++;
    }
    System.out.println("\nIt took " + count + " guesses to guess " + answer + ".");
    System.out.println("\nWould you like to play again (Y/N)?");
            String decision = input.nextLine(); // The program skips this input
            decision = decision.toUpperCase();
        while(decision.equals("Y"))
        {
    System.out.println("Guess a number between 1 and 10.");
    count = 1;
    guess = input.nextInt();
        answer = random.nextInt(1) + 1;

    while(guess != answer)
    {
        System.out.println("Wrong answer. Try again.");
        guess = input.nextInt();
        count++;
    }
    System.out.println("\nIt took " + count + " guesses to guess " + answer + ".");
    System.out.println("\nWould you like to play again (Y/N)?");
            decision = input.nextLine();
            decision = decision.toUpperCase();                
        }    
System.out.println("Thanks for playing.");
}

0 个答案:

没有答案