Hangman游戏开发疑问:为何randomword无法调用.length方法?
问题原因及解决方案
为什么不能用randomword.length?
randomword是你定义的Dictionary类对象,但你的Dictionary类里既没有length成员变量,也没提供length()方法,自然没法直接通过它获取单词长度。- 更关键的是,你调用
randomword.getWord(int_random)时,只是执行了方法却没保存它返回的String类型单词,等于白调用,根本没拿到要猜的目标单词。
修复步骤
- 保存目标单词:调用
getWord()后把返回值存到String变量里:
String targetWord = randomword.getWord(int_random);
- 获取单词长度:利用String类自带的
length()方法获取长度,替换原来的randomword.length:
char[] letters = new char[targetWord.length()];
- 处理非法索引:建议判断返回值是否为"Illegal index",避免后续逻辑出错:
if (targetWord.equals("Illegal index")) { System.out.println("无效的单词索引,请调整upperbound的值"); return; }
修改后的Main类代码示例
import java.util.Scanner; import java.util.Random; public class Main { public static void main(String[] args) { Random rand = new Random(); Dictionary randomword = new Dictionary(); // 用Dictionary的单词总数作为随机上限,避免越界 int upperbound = randomword.getWordCount(); int int_random = rand.nextInt(upperbound); Dictionary S1 = new Dictionary(); S1.printInfo(); // 保存目标单词 String targetWord = randomword.getWord(int_random); // 处理非法索引情况 if (targetWord.equals("Illegal index")) { System.out.println("无效的单词索引,请检查程序配置"); return; } // 通过String的length()获取单词长度 char[] letters = new char[targetWord.length()]; int lives = 8; Scanner answer = new Scanner(System.in); while (lives > 0) { System.out.println("You have " + lives + " guesses left."); // 显示当前猜测进度:下划线代表未猜中字母 for(int i= 0; i < targetWord.length(); i++) { System.out.print(letters[i] == '\u0000' ? "_ " : letters[i] + " "); } System.out.println(); System.out.println("Your guess:"); String guess = answer.nextLine(); // 校验输入格式 if (guess.length() != 1) { System.out.println("请输入单个字母!"); continue; } char letter = guess.toUpperCase().charAt(0); // 判断字母是否存在于目标单词中 boolean found = false; for (int i = 0; i < targetWord.length(); i++) { if (targetWord.charAt(i) == letter) { letters[i] = letter; found = true; } } if (!found) { lives--; System.out.println("猜错了!"); } // 判断是否猜完所有字母 boolean completed = true; for (char c : letters) { if (c == '\u0000') { completed = false; break; } } if (completed) { System.out.println("恭喜你猜对了!单词是:" + targetWord); break; } } if (lives == 0) { System.out.println("游戏结束,你用完了所有次数!正确单词是:" + targetWord); } answer.close(); } }
额外建议:优化Dictionary类
用switch-case存40个单词太繁琐,改成数组存储更易维护:
public class Dictionary { private String[] words = { "UNIVERSITY", "PROGRAMMING", "HANGMAN", // 补充剩余37个单词 }; public String getWord(int index) { if (index >= 0 && index < words.length) { return words[index]; } else { return "Illegal index"; } } // 获取单词总数,避免随机索引越界 public int getWordCount() { return words.length; } public void printInfo() { System.out.println("欢迎来到Hangman游戏!"); } }
内容的提问来源于stack exchange,提问作者Smn666x
相关产品推荐
相关产品推荐

