如何在整个Java类中创建变量?

时间:2018-07-25 21:25:04

标签: java class methods

我有一个询问用户名然后返回它的方法。现在,我想用另一种方法访问用户名,但是当我打印用户名时,它显示为“ null”。我不明白,我定义了变量,但是如何赋予整个类访问它的权限?

public static String userName() {
        Scanner input = new Scanner (System.in);

        System.out.print("Hello! Welcome to The Game. Whats your name? ");
        String userName = input.next();

        return userName;
}

这是我尝试访问userName变量但被赋予“ null”的方法

public static void homeMethod() {
        Scanner input = new Scanner (System.in);

        System.out.println("Hello " + userName + "! What would you like to do? (Type LIST for options)");
        String userGameChoice = input.nextLine();
}

在homeMethod()内部调用userName()方法时,也会遇到相同的错误。

非常感谢您的帮助。谢谢!

3 个答案:

答案 0 :(得分:1)

我需要在方法之外创建userName变量。

这就是我所拥有的:

public class MainGameClass {
    public static String userName;

    public static String userName() {
    Scanner input = new Scanner (System.in);

    System.out.print("Hello! Welcome to The Game. Whats your name? ");
    String userName = input.next();

    return userName;
    }

    public static void homeMethod() {
    Scanner input = new Scanner (System.in);

    System.out.println("What would you like to do " + userName + "? (Type LIST for options)");
    String userGameChoice = input.nextLine();
    }
}

调用homeMethod()时的输出:

您想做什么为空? (输入LIST作为选项)

解决方案:

public class MainGameClass {
    public static String userName;

    public static String userName() {
    Scanner input = new Scanner (System.in);

    System.out.print("Hello! Welcome to The Game. Whats your name? ");
    String userName = input.next();

    return userName;
    }

    public static void homeMethod() {
    Scanner input = new Scanner (System.in);

    System.out.println("What would you like to do " + userName + "? (Type LIST for options)");
    userGameChoice = input.nextLine();
    }
}

调用homeMethod()时的输出:

您想做什么(用户名)? (输入LIST作为选项)

说明:

我在类中正确定义了userName变量,但是,在userName()方法中,我使用相同的名称创建了一个新变量。因此,不要将答案返回给userName变量。

答案 1 :(得分:0)

在方法本身之外的类中声明 userName 变量,或者在您的 homeMethod 中调用 userName 方法,如下所示:

public static void homeMethod() {
    Scanner input = new Scanner (System.in);
    System.out.println("Hello " + userName() + "! What would you like to do? (Type LIST for options)");
    String userGameChoice = input.nextLine();

}

答案 2 :(得分:0)

您必须将userName移出这样的方法:

System.out.print("Hello! Welcome to The Game. Whats your name? ");
String userName = input.next()

public static String userName() {
    Scanner input = new Scanner (System.in);
    return userName;
}