如何在单独的方法中获取用户输入?

时间:2013-03-20 11:11:21

标签: java methods user-input

在我的方法“移动”中,我正在向用户打印指令。在方法“游戏”中,我需要通过使用方法“usersMove”来获取用户输入并使程序根据用户输入执行不同的操作。我最初在方法“移动”中扫描了我的用户输入,但该方法必须保持无效。有没有办法在“游戏”方法中获取用户输入,以便我可以将其值应用于其他方法?

public static void move()
    {
        System.out.print("What do you want to do?");
    }

public static void usersMove(String playerName, int gesture)
{
    int userMove = game(); 

    if (userMove == -1)
    {
        System.exit(0);
    }
}

public static void game()
{
    move();
    Scanner scan = new Scanner(System.in);
    int userMove = scan.nextInt();
}

2 个答案:

答案 0 :(得分:0)

使扫描仪scan保持静态,同时将初始化保持在game()内,然后在需要值的任何地方使用它。

答案 1 :(得分:0)

首先,使用像这样的静态方法对于“真正的”程序来说真的是不好的做法,但我认为这是一个Java学习练习...请记住,如果你这样做是这样的未来,你可能做错了。

使userMove为静态,如方法:

private static int userMove = -2; // or whatever value to indicate there's no move

然后在相同类的静态方法中使用它:

public static void usersMove(String playerName, int gesture)
{
    // just for fun, to catch bugs
    if (userMove < -1) {
        throw new IllegalStateException("illegal userMove value " + userMove);
    }

    if (userMove == -1)
    {
        System.exit(0);
    }
}

public static void game()
{
    move();
    Scanner scan = new Scanner(System.in);
    userMove = scan.nextInt();
}

阅读例如this以了解Java中的static

相关问题