Java控制台彩票游戏开发:输入数组值比对、未猜数隐藏及行完成状态跟踪
Java控制台彩票游戏核心功能实现方案
基于已完成的3行9列随机数卡生成逻辑(规则匹配:列对应固定数值区间、0值为空白不参与游戏、单行列5个有效数值),三个核心需求的实现逻辑如下:
1. 用户输入数字与卡面有效数值的匹配比对
匹配逻辑核心为逐位置遍历卡面二维数组,跳过0值空白位,将剩余有效数值与用户输入做等值判断:
- 用
Scanner接收控制台用户输入的整数 - 双层循环遍历3行9列的卡面数组
- 遇到值为0的空白位直接跳过,不参与比对
- 遇到与用户输入相等的非0值,判定为匹配成功
核心代码片段:
// 需提前导入import java.util.Scanner; Scanner scanner = new Scanner(System.in); int userGuess = scanner.nextInt(); boolean isMatched = false; for (int i = 0; i < cartao.length; i++) { for (int j = 0; j < cartao[i].length; j++) { if (cartao[i][j] == 0) continue; // 跳过空白位 if (cartao[i][j] == userGuess) { isMatched = true; // 记录命中位置,供后续状态跟踪使用 } } }
2. 未猜中数值的隐藏展示 + 全猜对的循环流程
核心思路是单独维护一套与卡面维度一致的猜中状态数组,不修改原始存真实值的卡面数组:
- 初始化
boolean[][] revealed = new boolean[3][9],所有位置默认false,代表对应位置的数值未被猜中 - 匹配命中后,将对应位置的
revealed值改为true - 渲染卡面时逐位置判断:
- 原数组为0的空白位:输出空白占位
revealed为true:输出对应位置的真实数值revealed为false:输出X占位隐藏真实值
- 循环终止条件:已猜中的有效数值数量达到总有效数(3行*每行5个=15个)时,退出循环并输出获胜提示
核心实现代码:
boolean[][] revealed = new boolean[3][9]; final int TOTAL_VALID_NUM = 15; int matchedCount = 0; while (matchedCount < TOTAL_VALID_NUM) { // 渲染当前隐藏状态的卡面 for (int i = 0; i < cartao.length; i++) { StringBuilder rowDisplay = new StringBuilder(); for (int j = 0; j < cartao[i].length; j++) { if (cartao[i][j] == 0) { rowDisplay.append(" "); // 空白位占两位宽度 } else if (revealed[i][j]) { rowDisplay.append(String.format("%02d", cartao[i][j])); // 猜中则展示真实值,补零对齐 } else { rowDisplay.append(" X"); // 未猜中展示X占位 } rowDisplay.append(" "); } System.out.println(rowDisplay); } // 接收用户输入并匹配 System.out.print("请输入猜测的数字:"); int guess = scanner.nextInt(); for (int i = 0; i < cartao.length; i++) { for (int j = 0; j < cartao[i].length; j++) { if (cartao[i][j] == guess && !revealed[i][j]) { revealed[i][j] = true; matchedCount++; System.out.println("猜对!"); } } } } System.out.println("恭喜你猜中所有数字,游戏获胜!");
3. 单行全猜中的状态跟踪与提示
基于已有的revealed状态数组,逐行检查有效位的猜中情况,无需额外存储大维度数据:
- 逐行遍历,仅检查该行内原数组非0的有效位置(跳过0值空白位)的
revealed状态 - 若某行所有有效位置的
revealed值均为true,则判定该行已全部猜中 - 增加3长度的标记数组
boolean[] rowCompleted = new boolean[3],记录每行是否已经触发过全中提示,避免重复弹窗
核心代码片段:
boolean[] rowCompleted = new boolean[3]; // 每次猜中状态更新后执行行检查 for (int rowIdx = 0; rowIdx < 3; rowIdx++) { if (rowCompleted[rowIdx]) continue; boolean isRowAllMatched = true; for (int colIdx = 0; colIdx < 9; colIdx++) { if (cartao[rowIdx][colIdx] == 0) continue; // 跳过空白位 if (!revealed[rowIdx][colIdx]) { isRowAllMatched = false; break; } } if (isRowAllMatched) { rowCompleted[rowIdx] = true; System.out.println("提示:第" + (rowIdx + 1) + "行的所有数字已全部猜中!"); } }
内容的提问来源于stack exchange,提问作者suRGE
相关产品推荐
相关产品推荐

