You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java多维数组实现高尔夫得分跟踪器 计算展示每位球员个人得分

高尔夫得分跟踪器总分计算实现方案

实现逻辑说明

你原有代码采用int[5][10]二维数组存储得分,索引从1开始使用,预留了第0位空间未存储有效数据,仅需要在得分录入完成后,遍历对应索引范围累加每位球员的所有洞得分即可。以下同时提供for循环和你要求的while循环两种实现版本,可直接替换原有main方法逻辑:

完整可运行代码

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class JavaClass {
    public static void main(String[] args) {
        // 初始化得分存储数组:5位玩家(用1-4位)、10个洞(用1-9位)
        int[][] multi = new int[5][10];
        // 原有得分录入逻辑
        for(int p = 1; p < 5; p++) {
            for(int h = 1;h < 10;h++) {
                System.out.println("Enter the score for Player " + p + ", Hole " + h + " :");           
                String v = stringReader();
                multi[p][h] = Integer.parseInt(v);
                System.out.println(v);
            }
        }

        // 新增:for循环版本计算总分(逻辑直观易维护,推荐使用)
        for(int p = 1; p < 5; p++) {
            int total = 0;
            for(int h = 1; h < 10; h++) {
                total += multi[p][h];
            }
            System.out.println("球员" + p + "总得分:" + total);
        }

        /* 新增:while循环版本计算总分(符合你尝试的实现方式)
        int p = 1;
        while(p < 5) {
            int total = 0;
            int h = 1;
            while(h < 10) {
                total += multi[p][h];
                h++;
            }
            System.out.println("球员" + p + "总得分:" + total);
            p++;
        }
        */
    }

    public static String stringReader() {
        String value;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        try {
            value = bufferedReader.readLine();
        } catch (IOException e) {
            value = "0";
        }
        return value;
    }
}

常见错误排查

如果你之前写的while循环无法输出结果,大概率是以下原因:

  • 循环变量未正确初始化,或者累加时使用了索引0的无效数据
  • 总得分变量未在每个球员计算前重置为0,导致得分累加错误
  • 循环条件写错,比如写成p <=5/h<=10触发数组越界

内容的提问来源于stack exchange,提问作者Sami Jaffri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 09:39:05