Java开发Penny Pitch游戏 实现硬币落点输出P标记的问题求解
Penny Pitch投便士游戏Java程序解决方案
核心问题点
- 生成硬币落点时仅读取了对应位置的数值,未存储行、列坐标,无法定位要标记为
P的单元格 - 初始化的
penny字符串数组默认全为P,不符合需求,应该初始化为和原数字棋盘一致的内容,仅替换硬币落点为P - 棋盘打印逻辑重复冗余,可通过双层循环简化实现
修正后可运行代码
import java.util.Random; import java.util.Scanner; public class PennyPitch { public static void main(String [] args){ Scanner reader = new Scanner(System.in); Random gen = new Random(); int total = 0; // 原数字棋盘 int [][] scoreArray = {{1,1,1,1,1}, {1,2,2,2,1}, {1,2,3,2,1}, {1,2,2,2,1}, {1,1,1,1,1}}; // 初始化显示用棋盘,和原棋盘数值一致 String [][] displayBoard = new String[5][5]; for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ displayBoard[i][j] = String.valueOf(scoreArray[i][j]); } } System.out.println("Press Enter to commence penny operation."); reader.nextLine(); // 打印初始棋盘 for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ System.out.print(scoreArray[i][j] + " "); } System.out.println(); } // 存储5枚硬币的坐标,格式为[行,列] int[][] pennyPositions = new int[5][2]; for(int i=0;i<5;i++){ int row = gen.nextInt(5); int col = gen.nextInt(5); pennyPositions[i][0] = row; pennyPositions[i][1] = col; // 累加对应位置数值 total += scoreArray[row][col]; // 标记对应位置为P displayBoard[row][col] = "P"; } System.out.print("\nPress Enter for total"); reader.nextLine(); System.out.print("\ntotal is: " + total + "\n"); System.out.print("\nPress Enter to display where the pennies landed"); reader.nextLine(); // 打印带P标记的棋盘 for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ System.out.print(displayBoard[i][j] + " "); } System.out.println(); } reader.close(); } }
补充优化说明
如果需要避免硬币重复落在同一个位置,可以在生成坐标的时候加去重判断,确保5个落点均不重复。
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

