【发布时间】:2015-03-04 18:33:23
【问题描述】:
好的,我的主类中有一个方法可以从文件中获取随机单词。我有一个表格,我希望能够从其他班级获得那个随机单词。我对公共变量不太熟练,对它们缺乏了解。也欢迎任何建议。谢谢!
public class Project {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
throws IOException
{
pickWord();
frmPlaying.main(args);
//To be honest I only know this shows the form and don't know why
}
public static void pickWord()
throws IOException
{
File words = new File("wordList.txt");
String wordToArray = new String();
String[] arrWord = new String[3863];
Scanner sc = new Scanner(words);
Random rWord = new Random();
int i = 0;
do
{
sc.nextLine();
wordToArray = sc.next();
arrWord[i] = wordToArray;
i++;
}while(sc.hasNext());
Arrays.toString(arrWord);
int idx = rWord.nextInt(arrWord.length);
String randomWord = (arrWord[idx]);
return randomWord;
}
}
^^^^ 获取随机词
/* try
{
Project.pickWord();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
*/
获取随机词的疑似代码
【问题讨论】:
-
不抛出 IOException 类型
return randomWord,而是将返回类型更改为 String 并使用String word = Project.pickWord()访问它。 -
问题为什么你的方法是静态的?你能分享剩下的课程吗?
-
它是静态的,因为我一开始以为是你公开它的方式,从那以后就没有改变过。
标签: java class variables public