首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在整个java类中创建变量?

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

Stack Overflow用户
提问于 2018-07-26 05:25:04
回答 2查看 40关注 0票数 2

我有一个请求用户名的方法,然后返回它。现在我想用另一种方法访问用户名,但是当我打印用户名时,它显示为"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()方法时,我遇到了同样的错误。

任何帮助都是非常感谢的。谢谢!

EN

回答 2

Stack Overflow用户

发布于 2018-07-26 05:33:21

我需要在方法外部创建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()时的输出:

您想做什么null?(键入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()时的输出:

你想做什么(userName)?(键入LIST以查看选项)

解释:

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

票数 1
EN

Stack Overflow用户

发布于 2018-07-26 19:46:39

您必须像这样将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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51527882

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档