隐藏短语游戏Java程序:实现大小写不敏感的字母匹配
解决隐藏短语游戏的大小写忽略匹配问题
要实现忽略大小写的字母匹配,只需修改字符比较逻辑,同时保留原短语的大小写格式,以下是具体方案:
关键修改点
- 将字符比较逻辑改为统一转成小写(或大写)后判断相等,确保输入的大小写不影响匹配结果
- 匹配成功时,使用原短语中的字符填充,保证显示内容和原短语的大小写一致
修改后的完整代码
package main; import java.util.*; public class Main { public static void main(String[] args) { int choice; Scanner input = new Scanner(System.in); System.out.print("Please enter your name: "); String name = input.nextLine(); Player player = new Player(); player.setName(name); do { System.out.println("--------------------------------"); System.out.println("Welcome to the Hidden Word Game!"); game(player); System.out.println("--------------------------------"); System.out.println("Would you like to play again?\n1: Yes\n2: No"); System.out.print("Enter your choice: "); choice = input.nextInt(); // 处理nextInt后的换行符,避免后续nextLine读取空字符串 input.nextLine(); } while (choice != 2); } public static void game(Player player) { Scanner input = new Scanner(System.in); String[] wordList = new String[] {"cruise ship", "soft drink", "National Football League", "New York", "little girl"}; String randomWord = wordList[(int)(Math.random() * wordList.length)]; StringBuilder word = new StringBuilder(); for (int i = 0; i < randomWord.length(); i++) { if (randomWord.charAt(i) == ' ') { word.append(' '); } else { word.append('*'); } } char[] hiddenWord = randomWord.toCharArray(); System.out.println("--------------------------------"); while(true) { System.out.println("Secrect Word :" + word); System.out.print("Guess one or more letters : "); player.setAttempts(); boolean correct = false; char [] guess = input.nextLine().toCharArray(); for(int i = 0 ; i < hiddenWord.length; i++) { for (int j = 0; j < guess.length; j++) { // 修改:统一转小写后比较,忽略大小写差异 if (Character.toLowerCase(guess[j]) == Character.toLowerCase(hiddenWord[i])) { // 修改:使用原短语字符,保留原始大小写 word.setCharAt(i, hiddenWord[i]); correct = true; } } } if (!correct) { System.out.println("You chose incorrect"); } else { System.out.println("You chose correct"); } System.out.println("--------------------"); if (randomWord.equals(word.toString())) { System.out.println("Congratulations " + player.getName() + " You Guessed The Hidden Word: " + randomWord); System.out.println("It took you " + player.getAttempts() + " attempts."); break; } } } }
额外优化说明
原代码中input.nextInt()后直接调用input.nextLine()会读取到空字符串,因此添加input.nextLine();处理换行符,避免游戏循环中出现异常。
内容的提问来源于stack exchange,提问作者Myrdock
相关产品推荐
相关产品推荐

