0

getWord() を介して返される文字列 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);

    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;    
}

これを機能させる方法はありますか?

String word = randomWord ;
randomWord が getWord() の文字列ではないため、唯一のエラーが発生します 。

では、randomWord を getWord() で使用できるようにするにはどうすればよいでしょうか。

編集: 既存のプライベートを変更することはできません。プライベートのままにしておく必要があります。

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 に答える