Hangman游戏报错Index 0 out of bounds for length 0求助
解决Hangman游戏的"Index 0 out of bounds for length 0"错误
错误根源
报错触发在CharacterSearch()方法的key.charAt(0)调用,核心问题是:
- 使用
input.nextInt()选择菜单后,输入缓冲区残留了换行符 - 后续首次调用
input.nextLine()时,会直接读取到这个空换行符,导致choice1成为空字符串 - 空字符串调用
charAt(0)必然触发索引越界异常
修复步骤
- 清除换行符残留:在
choice = input.nextInt();后添加input.nextLine();,消耗缓冲区里的换行符,确保后续nextLine()能正确读取用户输入的字母。 - 添加输入校验:读取用户猜测的字母后,检查输入是否为空或长度大于1,避免无效输入引发异常。
- 细节优化:把字符串拼接改为
StringBuilder提升效率,错误次数输出时根据数量自动调整单复数语法。
修复后的完整代码
package besingaPi_LE_3_2; import java.util.Scanner; public class GameHangman { public static void main(String[] args) { Scanner input = new Scanner(System.in); int miss = 0; String choice1; String temp; String[] words = {"giraffe", "hipopotamus", "gorilla", "peacock", "armadillo"}; int choice; mainMenu(); choice = input.nextInt(); input.nextLine(); // 清除nextInt()后的换行符 System.out.println(); if(choice == 1){ String wordRandom = Randomizer(words); String mute = secretWord(wordRandom); temp = mute; System.out.println(wordRandom); System.out.println("Note: use only small character/s"); while(!mute.equals(wordRandom)) { System.out.print("(Guess) Enter a letter in word " + mute + " > "); choice1 = input.nextLine().trim(); // 校验输入有效性 if(choice1.isEmpty() || choice1.length() != 1) { System.out.println("Please enter a single lowercase letter!"); continue; } mute = CharacterSearch(wordRandom, mute, choice1); if(temp.equals(mute)) { miss++; } temp = mute; } System.out.println("The word is " + wordRandom + ". You missed " + miss + " time" + (miss !=1 ? "s" : "") + "."); } else if (choice == 0) { System.out.println("Thank you!!"); return; } } public static void mainMenu() { System.out.println("Welcome to Hangman"); System.out.println("[1]START\n[0]EXIT"); System.out.print("Please input your choice: "); } public static String CharacterSearch(String word, String muted, String key) { StringBuilder update = new StringBuilder(muted); for(int i = 0; i < word.length(); i++) { if(word.charAt(i) == key.charAt(0)) { update.setCharAt(i,key.charAt(0)); } } return update.toString(); } public static String secretWord(String word) { StringBuilder temp = new StringBuilder(); for(int i = 0; i < word.length(); i++) { temp.append("*"); } return temp.toString(); } public static String Randomizer(String[] words) { int rand = (int)(Math.random() * words.length); return words[rand]; } }
内容的提问来源于stack exchange,提问作者Piolo Pascual Besinga
相关产品推荐
相关产品推荐

