我试图生成一个代码,询问用户的名称,然后打印他稍后输入的名称,但打印时变量为null。如何在不更改询问用户名的方法的情况下修复此问题,直到用户喜欢为止(我在我想要名字印上“?”的地方做了标记
public class Main {
static class NamingClass {
String PlayerName;
static void ChooseName() {
System.out.println("Enter your name:");
Scanner ScanPlayerName = new Scanner(System.in);//Object in scanner for name
NamingClass ObjForName = new NamingClass();//Object to use "PlayerName" String
ObjForName.PlayerName = ScanPlayerName.nextLine(); //ask user to enter name
System.out.println("Your name is " + ObjForName.PlayerName + ", is this correct?");
System.out.println("True=Yes");
System.out.println("False=No");
Scanner ObjToCheck = new Scanner(System.in); //Object in scanner for name check
Boolean CheckName = ObjToCheck.nextBoolean(); //boolean is asked to user
if(CheckName == false) {
ChooseName(); //repeat
}
else{
}
}
}
static void Credits() { //method that should print name entered in ChooseName()
System.out.println("The player name is" /* + ?????????????*/);
}
public static void main(String[] args) {
NamingClass.ChooseName();
Credits();
}
}
2条答案
按热度按时间l7wslrjt1#
您的错误是在中创建对象
chooseName
. 对象在方法调用后被销毁并丢失。。。这就是你需要的。。00jrzges2#
我认为在调用函数时应该传递name变量。
要获取名称,namingclass.choosename()将返回名称
然后打电话:
代码如下: