简体   繁体   中英

Is it possible to declare a scanner variable inside a method in Java to read keyboard input?

final int MAX_ROUNDS = 5;
String name1,name1;

Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter player1 name: ");
name1 = keyboard.nextLine();
System.out.println("Please enter player2 name: ");
name2 = keyboard.nextLine();
Player player1 = new Player(name1);
Player player2 = new Player(name2);

Dealer dealer = new Dealer();

    for(int count = 1; count <=MAX_ROUNDS; count++)
    {
        System.out.println("------------------");
        System.out.ptintf("Round : %d",count);
        dealer.rollDice();
        player1.makeGuess();
        player2.makeGuess();
        roundResults();

excerpt from the makeGuess method which belongs to the Player class.

public void makeGuess()
{
Scanner keyboard = new Scanner(System.in)

System.out.printf("Please guess 'even' or 'odd' "+
        "%s.", name);
String answer = keyboard.nextLine();

        if(answer.equalsIgnoreCase("even")
            guess = "Cho (even)";
        else
            guess = "Han (odd);
  }

I am not being prompted anything when the method executes I cannot understand why I did not include everything for the program. was just wondering if anyone eye balling this code could see something obvious otherwise, i will just take out the guess submission.

虽然我找不到您的代码有什么问题,但是,如果我不得不进行有根据的猜测,那么Dealer.dice()方法可能会陷入无限循环,这会导致整个程序出现故障

Have you tried to print out name1, name2, etc. variables that get their values from the scanner to see if it is working? Try doing that immediately after setting their value to be keyboard.nextLine(). This should then give you a better idea of where the problem lies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM