java 在方法中使用 Scanner

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15961823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:27:59  来源:igfitidea点击:

Utilizing a Scanner inside a method

javamethodsinput

提问by Marshall Tigerus

I'm new to programming, so I apologize if there is a very simple answer to this, but I cannot seem to find anything that actually. I am using a scanner object for user input in a guess your number game. The scanner is declared in my main method, and will be used in a single other method (but that method will be called all over the place).

我是编程新手,所以如果对此有一个非常简单的答案,我深表歉意,但实际上我似乎找不到任何东西。我在猜数字游戏中使用扫描仪对象进行用户输入。扫描器在我的 main 方法中声明,并将在一个其他方法中使用(但该方法将在所有地方被调用)。

I've tried declaring it as static, but eclipse has a fit over that and won't run.

我试过将它声明为静态的,但是 eclipse 适合它并且不会运行。

 public static void main(String[] args) {
    int selection = 0;
    Scanner dataIn = new Scanner(System.in);
    Random generator = new Random();
    boolean willContinue = true;

    while (willContinue)
    {
        selection = GameList();

        switch (selection){
        case 1: willContinue = GuessNumber(); break;
        case 2: willContinue = GuessYourNumber(); break;
        case 3: willContinue = GuessCard(); break;
        case 4: willContinue = false; break;
        }

    }



}

public static int DataTest(int selectionBound){
    while (!dataIn.hasNextInt())
    {
        System.out.println("Please enter a valid value");
        dataIn.nextLine();
    }

    int userSelection = dataIn.nextInt;
    while (userSelection > selectionBound || userSelection < 1)
    { 
        System.out.println("Please enter a valid value from 1 to " + selectionBound);
        userSelection = dataIn.nextInt;
    }


    return userSelection;
}

回答by dasblinkenlight

The reason why you see these errors is that dataInis localto the mainmethod, meaning that no other method can access it unless you explicitly pass the scanner to that method.

为什么你看到这些错误的原因是dataIn本地main方法,这意味着没有其他方法可以访问它,除非你明确地传递扫描仪那个方法。

There are two ways of resolving it:

有两种解决方法:

  • Passing the scanner to the DataTestmethod, or
  • Making the scanner staticin the class.
  • 将扫描器传递给DataTest方法,或
  • static在课堂上制作扫描仪。

Here is how you can pass the scanner:

以下是您可以通过扫描仪的方法:

public static int DataTest(int selectionBound, Scanner dataIn) ...

Here is how you can make the Scannerstatic: replace

以下是制作Scanner静态的方法:替换

Scanner dataIn = new Scanner(System.in);

in the main()with

main()

static Scanner dataIn = new Scanner(System.in);

outsidethe mainmethod.

main方法。

回答by ApproachingDarknessFish

You can't access variables declared in other methods, even the main method. These variables have method scopemeaning that they simply do not exist outside of the method in which they are declared. you can fix this by moving the declaration of Scanner outside of all of your methods. This way it will enjoy class scope and can be used anywhere within your main class.

您不能访问在其他方法中声明的变量,即使是 main 方法。这些变量具有方法范围,这意味着它们根本不存在于声明它们的方法之外。您可以通过将 Scanner 的声明移到所有方法之外来解决此问题。这样,它将享受类范围,并且可以在您的主类中的任何地方使用。

class Main{

     //this will be accessable from any point within class Main
     private static Scanner dataIn = new Scanner(System.in);

     public static void main(String[] args){ /*stuff*/ }

     /*Other methods*/
}

As a general rule of thumb in java, variables do not exists outside the smallest pair of {}in which they were declared (the sole exception being the {}that define the bodies of classes):

作为 java 中的一般经验法则,变量不存在{}于声明它们的最小对之外(唯一的例外是{}定义类的主体):

void someMethod() 
{ 
      int i; //i does not exist outside of someMethod
      i = 122;
      while (i > 0)
      {
           char c; //c does not exist outside of the while loop
           c = (char) i - 48;
           if (c > 'A')
           {
                boolean upperCase = c > 90; //b does not exist outside of the if statement
           }
      }



      {
          short s; //s does not exist outside of this random pair of braces
      }
}