Jeremy Hunts Jeremy Hunts - 1 month ago 20
Java Question

Constructor error, setter not working (Java)

I am a java beginner, Why does this code return null ? What is wrong with the constructor ? I set the name yet the sysout returns 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);
}
}

Answer

You declare new variables in the constructor instead of using the object variables.
Change it to

word(String n, int a, double c) {
    name=n;
    frequency=a;
    rel_freq=c;
}