【问题标题】:Get declared variable from different classes从不同的类中获取声明的变量
【发布时间】: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


【解决方案1】:

给你的方法一个返回类型。了解一下:http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

public static String pickWord()
    throws IOException{
....
String randomWord = (arrWord[idx]); /* Random Word I want this to be */
return randomWord;
}

【讨论】:

  • 好的,让它static 可以使它在其他类中可用。但是您根本没有解释,所以这对OP问题没有多大帮助。
  • 它是静态的,我不改变它。
  • 难道你不需要将String randomWord 也设为静态吗?
  • randomWord 静态?什么?它是方法内部的一个局部变量
  • OP:随机词我希望其他班级可以访问它,但不知道如何
猜你喜欢
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2020-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-09
  • 1970-01-01
相关资源
最近更新 更多