我有一个请求用户名的方法,然后返回它。现在我想用另一种方法访问用户名,但是当我打印用户名时,它显示为"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()方法时,我遇到了同样的错误。
任何帮助都是非常感谢的。谢谢!
发布于 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变量的答案。
发布于 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;
}
https://stackoverflow.com/questions/51527882
复制相似问题