我是一名java初学者,为什么这段代码会返回null?构造函数有什么问题?我设置了名称,但sysout返回null。
public class word {
String name;
int frequency;
double rel_freq;
word(String n, int a, double c) {
String name = n;
int frequency = a;
double rel_freq = c;
}
public static void main(String[] args) {
word maxwell = new word("bobo", 25, 40);
System.out.println(maxwell.name);
}
}
答案 0 :(得分:3)
您在构造函数中声明新变量,而不是使用对象变量 将其更改为
word(String n, int a, double c) {
name=n;
frequency=a;
rel_freq=c;
}
答案 1 :(得分:1)
构造函数声明与类实例变量名称相同的局部变量。不要在构造函数中使用dexlare locals。
换句话说;使用这个:“name = n”。 Inatead:“String name = n”。
答案 2 :(得分:-1)
package iran;
public class word {
String name;
int frequency;
double rel_freq;
word(String n, int a, double c) {
this.name = n;
this.frequency = a;
this.rel_freq = c;
}
public static void main(String[] args) {
word maxwell = new word("bobo", 25, 40);
System.out.println(maxwell.name);
System.out.println(maxwell.frequency);
System.out.println(maxwell.rel_freq);
}
}
您的本地变量,您必须设置实例变量Self // https://telegram.me/javalike