calling a method not getting result

2019-06-14 03:59发布

问题:

so im just trying to print a random word and thats it

Dictionary secret = new Dictionary();        
    secret.getRandomWord();        
    System.out.println(secret);

^all that is in my main program. And what was given to me that i have to use

 public String getRandomWord(){
    Random generator = new Random();
    String temp = new String();
    temp += dictionary[generator.nextInt(NUMBER_OF_WORDS)];
    return temp;

the above code is a class that was given to me that i have to work with. when i run my code i get program3.Dictionary@a37368 when it should be a random word. Any ideas?

回答1:

I think you are looking for

Dictionary secret = new Dictionary();
String randomWord = secret.getRandomWord();        
System.out.println(randomWord);

What you currently have is printing the result of toString() of the Dictionary object referenced by secret.


EDIT

Also possible without an extra variable:

Dictionary secret = new Dictionary();        
System.out.println(secret.getRandomWord());


回答2:

You are printing the Dictionary object, Try to store the return type of getRandomWord method and print the same.

String secretStr = secret.getRandomWord();
System.out.println(secretStr);


回答3:

Well, I think you need change your code.

Instead of:

Dictionary secret = new Dictionary();        
    secret.getRandomWord();        
    System.out.println(secret);

use:

Dictionary secret = new Dictionary();    
String randomWord = secret.getRandomWord(); 
System.out.println(randomWord); 

So, what's happen?