简体   繁体   English

是否可以在Java的方法中声明扫描程序变量以读取键盘输入?

[英]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. 摘录自Player类的makeGuess方法。

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? 您是否尝试过打印出名称1,名称2等变量,这些变量从扫描仪获取其值以查看其是否正常工作? Try doing that immediately after setting their value to be keyboard.nextLine(). 将其值设置为keyboard.nextLine()后立即尝试执行此操作。 This should then give you a better idea of where the problem lies. 这样可以使您更好地了解问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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