gpt4 book ai didi

Java - 2D 数组 - 主类和可实例化类 - 循环错误

转载 作者:行者123 更新时间:2023-12-01 09:22:37 27 4
gpt4 key购买 nike

我获得了有关 App 类和循环的帮助。

我遇到的错误是:

线程“main”中出现异常 java.lang.ArrayIndexOutOfBoundsException: 0在降雨量.Rainfall.compute引用:

   sum[i] = rain[i][j] + sum[i];

在rainfall.RainfallApp.main 引用:

    r.compute();)

C:\Users\~\run.xml:53: Java 返回: 1构建失败(总时间:5 秒)

可实例化类:

    import java.util.Arrays;
import javax.swing.JOptionPane;

public class Rainfall {
private int i;
private int j;
private int[][] rain = new int[4][7];
private int[] average = new int[4];
private int[] sum = new int[4];

public Rainfall(){
i = 0;
j = 0;
rain = new int[][]{};
average = new int[]{};
sum = new int[]{};
}

public Rainfall(int i, int j) {
this.i = i;
this.j = j;
}

public int getJ() {
return j;
}

public void setJ(int j) {
this.j = j;
}

public int getI() {
return i;
}

public void setI(int i) {
this.i = i;
}

public int[][] getRain() {
return rain;
}

public void setRain(int[][] rain) {
this.rain = rain;
}

public int[] getAverage() {
return average;
}

public void setAverage(int[] average) {
this.average = average;
}

public int[] getSum() {
return sum;
}

public void setSum(int[] sum) {
this.sum = sum;
}

public void compute(){

for (i = 0; i < rain.length; i++) {

for (j = 0; j < rain[0].length; j++) {
rain[i][j] = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter value"));

sum[i] = rain[i][j] + sum[i];
}

average[i] = sum[i] / rain[i].length;

}
}

public String returnAvg(){
return Arrays.toString(average);
}
}

APP文件:

    import javax.swing.JOptionPane;
import java.util.Arrays;

public class RainfallApp {

public static void main(String[] args) {

int[][] rain = new int[4][7];
int[] average = new int[4];



Rainfall r = new Rainfall();

r.setRain(rain);
r.compute();
average = r.getAverage();

JOptionPane.showMessageDialog(null, "The average for each week is: "+Arrays.toString(average));

}

最佳答案

您正在覆盖 Rainfall 类中的所有成员:

public Rainfall(){
i = 0;
j = 0;
rain = new int[][]{};
average = new int[]{};
sum = new int[]{}; // this is the problem
}

这样做有什么好处吗?在调用构造函数(作为成员)之前您已经给它们赋值了,那么为什么要覆盖它们呢?

稍后您调用 setRain() 来启动 rain 数组,但 sum 数组仍为空数组

关于Java - 2D 数组 - 主类和可实例化类 - 循环错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40069948/

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