【问题标题】:How do I call a variable from a void method in another class如何从另一个类中的 void 方法调用变量
【发布时间】:2019-03-26 01:06:29
【问题描述】:

如何从另一个类中的 void 方法调用字符串变量 user

我在运行此代码时经常遇到错误,因为 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);

}

}

【问题讨论】:

  • user 保持为空,因为您从未为其分配对象。
  • 您是否尝试在action 方法中设置user 的值?如果是这样,请将其更改为this.user = "hi";
  • 我从来没有给它分配对象是什么意思
  • 您分配的是局部变量而不是类字段。
  • 抱歉,我刚刚修改了它应该是的样子

标签: java class constructor


【解决方案1】:

这里是所有问题的总结:

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);

}

}

【讨论】:

  • 很抱歉它的 ActionEvent e,它也包含一个名为 getActionCommand() 的方法。我没有包含我所有的代码,因为它太长了
  • 没有全部代码很难理解。您至少应该提供一个工作示例。但是据我所知,这可能会给您带来问题: public void action(ActionEvent e){ this.user = "hi"; }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多