I set up a variable that I want returned, but it does not work.
The goal of this method is to create a random name generator which can be expanded as I see fit.
But it does not return the generatedFirstName
String. I looked through my notes over and over, but I can't find the error. Here is the code of the method:
public String weidenFirstName() {
ArrayList<String> firstNames = new ArrayList<String>();
firstNames.add("Ailfir");
//long list of more ArrayList elements
firstNames.add("Yann");
Random firstNamesRandom = new Random();
int r = firstNamesRandom.nextInt(firstNames.size());
String generatedFirstName = firstNames.get(r);
return generatedFirstName;
}
And here is the constructor that is supposed to execute the method and then save the generatedFirstName as another variable so it does not get deleted when the code is run for another object.
public NPC() {
weidenFirstName();
String FirstName = generatedFirstName;
}
I get the error: java: cannot find symbol
in the line where the firstName
String is set. And Inteliji also marks that variable as the source of the error.
The solution was simple. The return value of the method does not get stored in a variable. Thus the program cannot utilize it. To fix this I needed to do either this:
public NPC() {
String FirstName = weidenFirstName();;
}
or this:
public NPC() {
generatedFirstName = weidenFirstName();
String FirstName = generatedFirstName;
}
The return value of a method IS a value. The method weidenFirstName() IS a String. Also setting generatedFirstName in the method equal to something and then let the Method return void would have worked.
If you want to get the value from weidenFirstName()
in NPC()
method, you need to assign a new String equal to the returned value from weidenFirstName()
then assign that value equal to String FirstName
in NPC()
method. So you need to do like this in NPC()
method:
public void NPC() {
String generatedFirstName = weidenFirstName();
String FirstName = generatedFirstName;
}
In NPC() method, if you just want to assign the value FirstName
equal to the random value from weidenFirstName()
method then you do above. If you want to return the String value from it then you can do like below:
public String NPC() {
String generatedFirstName= weidenFirstName();
String FirstName = generatedFirstName;
return FirstName;
}