[英]How do i access variable of void method of other class from another class
[英]How do I call a variable from a void method in another class
如何從另一個類中的 void 方法調用字符串變量 user
我經常在運行此代碼時遇到錯誤,因為 getUser() 函數中的用戶不等於 action(ActionEvent j) 函數中的用戶。
阿爾法類:
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);
}
}
這里總結了所有問題:
阿爾法類:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.