我遇到的问题是,虽然我相信我已经在构造函数中正确设置了所有内容,当我尝试调用from我的新Letter实例的实例变量时,我fromto似乎不断收到错误,说编译器无法找到变量fromto.目标是Dylan使用Text显示.
public class Letter {
private String from; // Sets from instance variable to be stored
private String to; /// Sets to instance vaariable to be stored
public Letter(String from, String to) {
this.from = from;
this.to = to;
}
public Letter() {
Letter fromto = new Letter("Dylan", "April");
}
public static void main(String[] args) {
System.out.println("Dear " + fromto.from);
}
}
Run Code Online (Sandbox Code Playgroud)
首先,您可能应该了解有关Java中变量范围的更多信息.(阅读Sun关于面向对象的Java编程的教程可能是一个好主意)
这里的问题是变量fromto是在构造函数中声明的,因此只能从构造函数的作用域中获得.相反,摆脱构造的(除非你真的想保持它,在这种情况下,你应该确保初始化from和to变量正确)和变量移动到您的main功能.
public class Letter {
private String from; // Sets from instance variable to be stored
private String to; /// Sets to instance vaariable to be stored
public Letter(String from, String to) {
this.from = from;
this.to = to;
}
public static void main(String[] args) {
Letter fromto = new Letter("Dylan", "April");
System.out.println("Dear " + fromto.from);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52 次 |
| 最近记录: |