在Java中传递私有字符串
我需要通过getWord()获取要返回的字符串randomWord 你有什么办法让它工作吗 唯一的错误来自在Java中传递私有字符串,java,private,Java,Private,我需要通过getWord()获取要返回的字符串randomWord 你有什么办法让它工作吗 唯一的错误来自 字符串字=随机字 因为randomWord在getWord()中不是字符串 那么如何使randomWord可用于getWord() 编辑: 我无法更改任何现有的私有,它们必须保持私有。我假设这些方法属于一个类。首先删除静态修饰符。第二,制作字符串此类的私有成员 public class MyDictionary { String word; private void se
字符串字=随机字代码>
因为randomWord在getWord()中不是字符串
那么如何使randomWord可用于getWord()
编辑:
我无法更改任何现有的私有,它们必须保持私有。我假设这些方法属于一个类。首先删除静态
修饰符。第二,制作字符串代码>此类的私有成员
public class MyDictionary {
String word;
private void setUpDictionary() {
////////
word = words[rand];
////////
}
private String getWord() {
return word;
}
}
您正在将randomWord
设置为setUpDictionary()
方法中的新字符串对象。它应该是类的成员属性,这样就可以在类的作用域内的其他方法中引用它
例如:
private static String randomWord;
private static void setUpDictionary() throws IOException {
// ...
randomWord = words[rand];
// ...
}
private static String getWord() {
return randomWord;
}
静态方法无法做到这一点。您如何/在何处调用getword?无法更改隐私,它们必须保持隐私。@Brett这没问题。保密,不客气。正如其他人在这个帖子中所说,您应该重新考虑是否需要使这些方法成为静态的。您是否正在实例化它们所属的类,并因此使用引用?如果是这样,就去掉静态方法。相反,如果使用类名调用它们(就像使用Math.random()一样),则将它们保留在中。
private static String randomWord;
private static void setUpDictionary() throws IOException {
// ...
randomWord = words[rand];
// ...
}
private static String getWord() {
return randomWord;
}
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;
}