calling a method not getting result

寵の児 提交于 2019-12-23 05:29:15

问题


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?



来源:https://stackoverflow.com/questions/15695830/calling-a-method-not-getting-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!