Java 它是否返回一个空变量?

Java 它是否返回一个空变量?,java,Java,我现在在高中做一个刽子手项目。“newWord”是包含字典文件中随机选择的单词的变量。在makeList方法中,您可以看到它随机抽取单词。还有一个System.out.println(“this:+newWord”);因此,我可以测试是否成功地从外部文件中提取单词。然后它返回新词,但当返回到main方法时,它是空的,因此在程序的其余部分都是空的。有人能帮我解决这个问题吗 public class HangmanProject { public static void main(Strin

我现在在高中做一个刽子手项目。“newWord”是包含字典文件中随机选择的单词的变量。在makeList方法中,您可以看到它随机抽取单词。还有一个System.out.println(“this:+newWord”);因此,我可以测试是否成功地从外部文件中提取单词。然后它返回新词,但当返回到main方法时,它是空的,因此在程序的其余部分都是空的。有人能帮我解决这个问题吗

public class HangmanProject {
    public static void main(String args[]) {
        String newWord = " ";
        int letterNumber = 0;

        makeList(newWord); 

        countLetters(newWord, letterNumber);
        System.out.println("this: " + newWord);
        displayBoard(letterNumber, newWord); 
    } 

    public static String makeList(String newWord) { 
        do{
            try(Scanner s = new Scanner(new File("dictionary.txt"))) {
            ArrayList<String> list = new ArrayList<String>();
                while (s.hasNext()) {
                    list.add(s.next());
                }

            Random random = new Random();
            int index = random.nextInt(list.size());
            newWord = list.get(index);
            } catch (IOException e) {
                System.out.println("Error Found");
            }
        } while (!(newWord.length() >= 5));
        System.out.println("this: " + newWord);
        return newWord;
    }
公共类Hangman项目{
公共静态void main(字符串参数[]){
字符串newWord=“”;
int-letterNumber=0;
makeList(newWord);
计数字母(新词、字母编号);
System.out.println(“this:+newWord”);
显示板(字母编号、新词);
} 
公共静态字符串生成列表(字符串新词){
做{
try(Scanner s=新扫描仪(新文件(“dictionary.txt”)){
ArrayList=新建ArrayList();
而(s.hasNext()){
添加(s.next());
}
随机=新随机();
int index=random.nextInt(list.size());
newWord=list.get(索引);
}捕获(IOE异常){
System.out.println(“发现错误”);
}
}而(!(newWord.length()>=5));
System.out.println(“this:+newWord”);
返回新词;
}

您对返回的值不做任何处理。只需将其分配到某个位置,您就可以了。此外,由于
makeList
不使用其值,只需将其声明为局部变量:

String newWord = makeList(); 

哪里定义了
newWord
?在不同方法中声明的变量是不相关的,即使它们共享相同的名称。也就是说,main中的
newWord
和makeList中的
newWord
是独立的,分配给一个变量对另一个(不同)变量没有影响。makeList(newWord)无法在Main中保存返回字符串。请将其分配给变量或打印相同的变量。