0

I need to get the string randomWord to return through getWord()

    private static void setUpDictionary() throws IOException
{

    Scanner fileScan;
    String[] words = new String[25];

    fileScan = new Scanner (new File("dictionary.dat")); 
    int n=0;
    while (fileScan.hasNext())
    {
        words[n] = fileScan.next();
        n++; 
    }

    int rand = (int) (Math.random()*n);

    String randomWord = words[rand];
    System.out.println("TEST THIS IS RANDOM WORD ..." + randomWord);

    fileScan.close();
}

//Returns random word from dictionary array
private static String getWord()
{
    String word = randomWord ;
    return word;    
}

Any ideas how to get this to work?

The only error comes from String word = randomWord ;
because randomWord isn't a string in getWord().

So how do I make randomWord available to getWord()?

EDITS: I cannot change any existing private, they have to stay private.

4

3 回答 3

1

您在方法中设置randomWord为新的 String 对象setUpDictionary()。它应该是类的成员属性,以便可以在类范围内的其他方法中引用。

例子:

private static String randomWord;

private static void setUpDictionary() throws IOException {
    // ...
    randomWord = words[rand];
    // ...
}

private static String getWord() {
    return randomWord;
}
于 2013-05-12T08:14:56.317 回答
0

我假设这些方法属于一个类。首先删除static修饰符。其次,使String word;这个类的私有成员。

public class MyDictionary {
    String word;

    private void setUpDictionary() {
        ////////
        word = words[rand];
        ////////
    }

    private String getWord() {
        return word;
    }
}
于 2013-05-12T08:11:59.387 回答
0
private String randomWord="";
  private static void setUpDictionary() throws IOException
{

    Scanner fileScan;
    String[] words = new String[25];

    fileScan = new Scanner (new File("dictionary.dat")); 
    int n=0;
    while (fileScan.hasNext())
    {
        words[n] = fileScan.next();
        n++; 
    }

    int rand = (int) (Math.random()*n);

    randomWord = words[rand];
    System.out.println("TEST THIS IS RANDOM WORD ..." + randomWord);

    fileScan.close();
}

//Returns random word from dictionary array
public static String getWord()
{
try{
setUpDictionary();
}catch(Exception exp){}

return randomWord;
}
于 2013-05-12T08:21:16.587 回答