我得到了App类和循环的帮助。
我得到的错误是:
线程"main"异常java.lang.ArrayIndexOutOfBoundsException: 0在rainfall.Rainfall.compute参考:
sum[i] = rain[i][j] + sum[i];
at rain . rainfallapp .main参考:
r.compute();)
C:Users~run.xml:53: Java返回:1BUILD FAILED(总时间:5秒)
Instantiable类:
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);
}
}
应用程序文件:
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
数组仍然是空数组