gpt4 book ai didi

java - 数组困惑

转载 作者:行者123 更新时间:2023-12-01 08:03:47 25 4
gpt4 key购买 nike

我不是一名 get 程序员,我的代码一直存在问题。我收到错误:

`java.lang.ArrayIndexOutOfBoundsException: 0`

一些帮助将不胜感激。谢谢。

我的代码:

    import java.util.Scanner;
public class Gradebook1D {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] id = new int[0];
double[] quiz1 = new double[0];
double[] quiz2 = new double[0];
double[] quiz3 = new double[0];

int idStudent = 0;
System.out.print("Enter how student's are in your class: ");
idStudent = input.nextInt();

double[] sum = new double[0];
for (int i = 0; i < idStudent; i++){
System.out.println("Enter student ID: ");
id[i] = input.nextInt();

System.out.print("\n Enter score for Quiz1: ");
quiz1[i] = input.nextInt();

System.out.print("\n Enter score for Quiz2: ");
quiz2[i] = input.nextInt();

System.out.print("\n Enter score for Quiz3: ");
quiz3[i] = input.nextInt();

sum[i] = quiz1[i] + quiz2[i] + quiz3[i];
}
}
}

最佳答案

使用idStudent初始化idquiz1quiz2quiz3,如下所示

int[] id = new int[idStudent];
double[] quiz1 = new double[idStudent];
double[] quiz2 = new double[idStudent];
double[] quiz3 = new double[idStudent];

该错误的原因是您声明数组大小为零。您无法将元素插入到大小为零的数组中

关于java - 数组困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23211034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com