在方法内部使用扫描仪 [英] Utilizing a Scanner inside a method

查看:61
本文介绍了在方法内部使用扫描仪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

我尝试将其声明为静态,但是eclipse可以解决这个问题,并且无法运行.

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

 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;
}

推荐答案

看到这些错误的原因是 dataIn main 本地/code>方法,这意味着除非您将扫描程序显式传递给该方法,否则其他任何方法都无法访问它.

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

有两种解决方法:

  • 将扫描仪传递给 DataTest 方法,或
  • 在类中将扫描仪设置为 static .

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

Here is how you can pass the scanner:

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

这是使 Scanner 静态的方法:替换

Here is how you can make the Scanner static: replace

Scanner dataIn = new Scanner(System.in);

main()中的

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

外部 main 方法.

这篇关于在方法内部使用扫描仪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆