Unable to access scanner on nested if condition

baezl :

The expected output of the code is for a user to guess a randomly generated number between 0 to 100000, and for each guesses he pay $1.00, if the user guesses right he wins $1m, if not he is asked if he want a hint. each hint cost $2.00. so the code continues to run until the user quits the game or wins. the problem with my code is that after asking the user if he wants a hint or not the scanner input code doesn't run.

package com.company;

import java.util.Random;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int guess, toguess;
    String payOrQuit, yesOrNo;
    double totalSpent = 0.0, hint, value;
    boolean isWon = false, isQuit = false;
    Random rand = new Random();

    while (!isWon && !isQuit) {
      toguess = rand.nextInt(1000000);
      System.out.println("Want to win a million dollars?");
      System.out.println("If so, guess the winning number (a number between 0 and 100000).");
      System.out.print("Insert $1.00 and enter your number or 'q' to quit: ");
      payOrQuit = input.nextLine();
      if (payOrQuit.matches(".*\\d.*")) { // IF pays or quit
        value = Double.parseDouble(payOrQuit);
        System.out.println(toguess);
        System.out.print("Guess a number: ");
        guess = input.nextInt();
        if (guess == toguess) { // IF 2 starts
          System.out.println("YOU WIN!\nYou won $1000000!");
          isWon = true;
        } else {
          totalSpent += value;
          System.out.print("Sorry, good guess,Do you want me to give you a hint (y|n)?");
          yesOrNo = input.nextLine();
          if (yesOrNo.equals("y")) { // IF 3 starts
            System.out.print("Insert $2.00 for the hint! : ");
            hint = input.nextDouble();
            totalSpent += hint;
            if (guess > toguess) {
              System.out.println("Guessed number too high");
            } else {
              System.out.println("Guessed number too low");
            }
          } else {
            System.out.println("amount lost = " + totalSpent);
            isQuit = true;
          } // IF 3 ends
        } // IF 2 ends
      } else {
        System.out.println("amount lost = " + totalSpent);
        isQuit = true;
      } // IF pays or quit ends//
    }
  }
}
Arvind Kumar Avinash :

The problem is because of input.nextInt() and input.nextDouble().

guess = input.nextInt();

Change it to

guess = Integer.parseInt(input.nextLine());

Similarly, also change

hint = input.nextDouble();

to

hint = Double.parseDouble(input.nextLine());

Check Scanner is skipping nextLine() after using next() or nextFoo()? for more information.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=357428&siteId=1