如何在一种方法中将变量用于另一种方法?

时间:2018-10-13 20:55:08

标签: java variables methods static-methods

所以我想知道是否有人可以告诉我如何将一个方法中的变量调用/引用为另一方法。例如,

public static void main(String[] args) 
{
    System.out.println("Welcome to the game of sticks!");
    playerNames();
    coinToss();
}

public static void playerNames()
{
    Scanner input = new Scanner(System.in);
    System.out.println();

    System.out.print("Enter player 1's name: ");
    String p1 = input.nextLine();

    System.out.print("Enter player 2's name: ");
    String p2 = input.nextLine();

    System.out.println();
    System.out.println("Welcome, " + p1 + " and " + p2 + ".");
}

public static void coinToss()
{
    System.out.println("A coin toss will decide who goes first:");
    System.out.println();
    Random rand = new Random();
    int result = rand.nextInt(2);
    result = rand.nextInt(2);
    if(result == 0)
    {
        System.out.println(p1 + " goes first!");
    }
    else
    {
        System.out.println(p2 + " goes first!");
    }           
}

我想在coinToss()内使用来自playerNames()的p1和p2,所以我可以简单地宣布谁先进入,但我不知道如何调用变量。

我的问题与其他问题并没有什么不同,但是我无法理解其他人给出的答案。一旦我发布了这个,我就从一群好心人那里得到了答案:)

3 个答案:

答案 0 :(得分:0)

我假设您是Java的新手,因为您似乎不熟悉 fields 的概念(即,您可以将变量放在 outside 方法中)。

public class YourClass {
    static String p1;
    static String p2;

    public static void main(String[] args) 
    {
        System.out.println("Welcome to the game of sticks!");
        playerNames();
        coinToss();
    }

    public static void playerNames()
    {
        Scanner input = new Scanner(System.in);
        System.out.println();

        System.out.print("Enter player 1's name: ");
        p1 = input.nextLine();

        System.out.print("Enter player 2's name: ");
        p2 = input.nextLine();

        System.out.println();
        System.out.println("Welcome, " + p1 + " and " + p2 + ".");
    }

    public static void coinToss()
    {
        System.out.println("A coin toss will decide who goes first:");
        System.out.println();
        Random rand = new Random();
        int result = rand.nextInt(2);
        result = rand.nextInt(2);
        if(result == 0)
        {
            System.out.println(p1 + " goes first!");
        }
        else
        {
            System.out.println(p2 + " goes first!");
        }           
    }

}

答案 1 :(得分:0)

您要搜索的被称为实例变量,请检查一下。 https://www.tutorialspoint.com/java/java_variable_types.htm

答案 2 :(得分:0)

我要做的就是在外部创建实例/静态变量!像这样:

static String name1;
static String name2;

这很容易。谢谢大家的帮助!