Java石头剪刀布游戏计分功能实现问题求助
解决石头剪刀布游戏的计分统计问题
你的代码主要有两个核心问题导致计分失效:
- 计分变量
win、lose、tie被定义在while循环内部,每次循环都会被重置为0,根本无法累计分数 - 随机输出结果后没有根据结果对应更新分数,只是把更新代码注释掉了
这里是修正后的完整代码:
import java.util.Random; import java.util.Scanner; public class RockPaperScissors { // 类名首字母大写,符合Java命名规范 public static void main(String[] args) { Scanner input = new Scanner(System.in); Random random = new Random(); // 只创建一次Random对象,避免重复实例化 // 把计分变量移到循环外面,保证每次循环都能累计 int win = 0; int lose = 0; int tie = 0; while (true) { System.out.println("Please choose (r)ock, (p)aper or (s)cissors:"); String answer = input.nextLine().trim(); // 加trim()处理输入的空格 // 先处理无效输入的情况 if (!answer.equals("r") && !answer.equals("p") && !answer.equals("s")) { System.out.println("Invalid input! Please enter r, p or s."); continue; } int resultIndex = random.nextInt(3); // 先获取随机索引,方便后续判断结果 String resultMsg = ""; switch (answer) { case "r": switch (resultIndex) { case 0: resultMsg = "You chose rock. I chose paper. You lose!"; lose++; break; case 1: resultMsg = "You chose rock. I chose scissors. You win!"; win++; break; case 2: resultMsg = "You chose rock. I chose rock. We tie!"; tie++; break; } break; case "p": switch (resultIndex) { case 0: resultMsg = "You chose paper. I chose scissors. You lose!"; lose++; break; case 1: resultMsg = "You chose paper. I chose rock. You win!"; win++; break; case 2: resultMsg = "You chose paper. I chose paper. We tie!"; tie++; break; } break; case "s": switch (resultIndex) { case 0: resultMsg = "You chose scissors. I chose rock. You lose!"; lose++; break; case 1: resultMsg = "You chose scissors. I chose paper. You win!"; win++; break; case 2: resultMsg = "You chose scissors. I chose scissors. We tie!"; tie++; break; } break; } System.out.println(resultMsg); System.out.println("Score: " + win + " win(s), " + lose + " loss(es), " + tie + " tie(s)"); System.out.println("Play again (y/n)?"); String c = input.nextLine().trim(); if (c.equalsIgnoreCase("n")) { break; } } input.close(); // 关闭Scanner,避免资源泄漏 } }
关键修改点说明:
- 计分变量位置调整:把
win、lose、tie移到while循环外部,这样每次游戏循环都能保留之前的分数,实现累计统计。 - 先获取随机索引再判断:不再直接随机输出字符串,而是先拿到随机结果的索引,根据索引判断是赢、输还是平局,然后对应更新计分变量,最后再输出结果消息。
- 优化Random对象创建:只实例化一次
Random,避免每次循环都创建新对象,更符合Java性能规范。 - 增加无效输入处理:如果用户输入不是r/p/s,提示错误并跳过后续逻辑,提升用户体验。
- 代码规范优化:类名改为
RockPaperScissors(首字母大写,符合Java命名规范),添加trim()处理输入空格,最后关闭Scanner释放资源。
如果你不想用嵌套switch,也可以用if-else来替换,逻辑是一样的,比如:
// 以用户选r为例 if (answer.equals("r")) { if (resultIndex == 0) { resultMsg = "You chose rock. I chose paper. You lose!"; lose++; } else if (resultIndex == 1) { resultMsg = "You chose rock. I chose scissors. You win!"; win++; } else { resultMsg = "You chose rock. I chose rock. We tie!"; tie++; } }
内容的提问来源于stack exchange,提问作者user23019518
相关产品推荐
相关产品推荐

