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

Java数组传参返回索引报错:minIndex与maxIndex无法解析

代码错误修复方案

核心问题及解决步骤

  1. 未声明变量引发编译错误
    你在main方法里直接使用minIndex和maxIndex,但这两个变量从未被定义。需要调用你写的findIndexOfMin和findIndexOfMax方法,将返回值赋值给这两个变量后再使用。

  2. 非静态方法无法在静态上下文调用
    findIndexOfMax方法没有声明为static,而main方法是静态的,静态方法里不能直接调用非静态方法。只需给这个方法加上static修饰符即可。

修复后的完整代码

import java.util.*;

public class asgn6 {
    static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {       
        System.out.print("\nHow many teams do you want to enter: ");
        int teamNum = scanner.nextInt();
        scanner.nextLine();
        String[] team = new String[teamNum];
        int[] score = new int[teamNum];
        for(int i=0; i<teamNum; i++) {
            System.out.println("Team " + ((i)+1) + ": \nEnter team's name:\t");
            team[i] = scanner.nextLine();
            System.out.println("Enter team's score (400-1000):");
            score[i] = scanner.nextInt();
            scanner.nextLine();
        }
        for (int i=0; i<teamNum; i++) {
            System.out.println(team[i] + " " + score[i]);
        }
        // 调用方法获取索引
        int minIndex = findIndexOfMin(score);
        int maxIndex = findIndexOfMax(score);
        
        System.out.println("Losing team: " + team[minIndex] + " score: " + score[minIndex]);
        System.out.println("Winning team: " + team[maxIndex] + " score: " + score[maxIndex]);
    }

    public static int findIndexOfMin (int[] score) {
        int smallestValue = score[0];
        int minIndex = 0;
        for (int i = 0; i < score.length; i++){
            if (score[i] <= smallestValue){
                smallestValue = score[i];
                minIndex = i;
            }
        }
        return minIndex;
    }

    // 加上static修饰符
    public static int findIndexOfMax(int[] score) {
        int largestValue = score[0];
        int maxIndex = 0;
        for (int i = 0; i < score.length; i++){
            if (score[i] >= largestValue){
                largestValue = score[i];
                maxIndex  = i;
            }
        }
        return maxIndex;
    }
}

额外优化建议(可选)

  • 可以添加分数范围验证,确保输入的分数在400-1000之间,比如用循环直到输入符合要求:
do {
    System.out.println("Enter team's score (400-1000):");
    score[i] = scanner.nextInt();
    scanner.nextLine();
} while (score[i] < 400 || score[i] > 1000);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 07:30:39