如何从另一个类的void方法中调用字符串变量用户
运行此代码经常会出错,因为getUser()函数中的用户不等于action(ActionEvent j)函数中的用户。
Alpha类:
public class Alpha(){
private string user;
public Alpha(int temp){
temp = 0;
}
public void action(ActionEvent e){
String command = e.getActionCommand();
user = "hi";
}
public String getUser(){
return this.user;
}
主要:
public class Test {
public static void main(String[] args) {
Alpha n = new Alpha();
String username = n.getUser();
System.out.println(username);
}
}
答案 0 :(得分:0)
以下是所有问题的摘要:
Alpha类:
public class Alpha(){
private string user;
public Alpha(int temp){ why do you need a temp argument?
temp = 0; //why do you set temp at 0?
}
public void action(ActionEvent j){ // why do you need an ActionEvent j argument?
user = "hi";
}
public String getUser(){
return this.user;
}
主要:
public class Test {
public static void main(String[] args) {
Alpha n = new Alpha(); //you call a contructor but not the one you write -> Alpha(int temp)
String username = n.getUser();
/** you try to get the username here but it was never set (so it = null)
you set it in action(ActionEvent j), so you can try to insert
action(j);
**/
System.out.println(username);
}
}