Reputation: 57
My aim was to create a little bit of code which allows my computer to randomly select how it refers to me. "Hello " + (randomly selected nickname) + ", how are you today?"
Pretty simple, right? Not to a noob like me!
Referenced Class I gave it 4 choices of names, and it selects one at random and prints it out.
public class NameRef {
public static void main(String[] args){
ArrayList<String> nickNames = new ArrayList<String>();
nickNames.add("DJ");
nickNames.add("Buddy");
nickNames.add("Dude");
nickNames.add("Sir");
Random rand = new Random();
rand.nextInt(4);
System.out.println(nickNames.get(rand.nextInt(4)));
}
}
Main Class I wanted this class to take the information from that secondary class' function and reference to it in my greeting.
public class CodeTesting extends NameRef {
public static void main(String[] args) {
System.out.println("Hello, " + /*The product from the NameRef*/ + " how are you?");
}
}
I don't know how I am supposed to reference that information? I've tried is a hundred ways!
I also tried to make a function in the secondary class that RETURNED a name string but then I wasn't able to reference that in my main class...
I am so confused. Any help as to where I'm going wrong would be great. Thanks.
Upvotes: 2
Views: 96
Reputation: 43128
Change main
in NameRef
to a function that returns String
. So instead of System.out.println(nickNames.get(rand.nextInt(4)));
, it should instead do return nickNames.get(rand.nextInt(4))
. Then in CodeTesting
class, call the function like this:
public class CodeTesting extends NameRef {
public static void main(String[] args) {
System.out.println("Hello, " + nameOfFunction() + " how are you?");
}
}
Where nameOfFunction
is the name you call the function you created
Upvotes: 1
Reputation: 5316
public class NameRef {
public String getName(){
ArrayList<String> nickNames = new ArrayList<String>();
nickNames.add("DJ");
nickNames.add("Buddy");
nickNames.add("Dude");
nickNames.add("Sir");
Random rand = new Random();
rand.nextInt(4);
return nickNames.get(rand.nextInt(4));
}
}
public class CodeTesting extends NameRef {
public static void main(String[] args) {
NameRef nameRefObject = new NameRef();
System.out.println("Hello, " +nameRefObject.getName()+ " how are you?");
}
}
Upvotes: 0