我试图在可实例化的类中运行计算方法并且它无法正常工作。应用程序类似乎只是绕过它,我真的无法弄清楚为什么。 结果是:"每周的平均值是:[]"
App类:
package rainfall;
import javax.swing.JOptionPane;
//import java.util.Arrays;
public class RainfallApp {
public static void main(String[] args) {
Rainfall r = new Rainfall();
r.compute();
JOptionPane.showMessageDialog(null, r.getResult());
}
}
可实例化的课程:
package rainfall;
import java.util.Arrays;
import javax.swing.JOptionPane;
public class Rainfall {
private int[][] rain = new int[4][7];
private int[] average = new int[4];
private int[] sum = new int[4];
public Rainfall(){
rain = new int[][]{};
average = new int[]{};
sum = new int[]{};
}
public void compute(){
for (int i= 0; i < rain.length; i++) {
for (int j = 0; j < rain[0].length; j++) {
rain[i][j] = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter value"));
sum[i] = rain[i][j] + sum[i];
System.out.println(Arrays.toString(sum));
}
average[i] = sum[i] / rain[i].length;
}
}
答案 0 :(得分:1)
我想答案是:再次阅读有关数组的语法。
构造函数中的代码:
public Rainfall(){
rain = new int[][]{};
average = new int[]{};
sum = new int[]{};
根本没有任何意义。你知道,你已经在声明中初始化所有三个数组。你创建了完全有效的数组,然后在构造函数中覆盖......首先不需要它。
答案 1 :(得分:0)
我想首先询问您是否使用了调试器,并检查了变量的值。
从我提供的代码示例中我可以看到,我可以清楚地看到为什么你的for循环都没有运行。简单来说,你试图在空数组上运行循环。
你的数组为空的原因是你的构造函数,如下面的代码所示:
public class Rainfall {
private int[][] rain = new int[4][7];
private int[] average = new int[4];
private int[] sum = new int[4];
public Rainfall(){
rain = new int[][]{};
average = new int[]{};
sum = new int[]{};
}
}
在提供的示例中,构造函数将使用空数组覆盖已分配给字段的值。您需要决定是否要直接(不推荐)或在构造函数(推荐)中为字段赋值,而不是两者。贝娄是上面解释的两个选项:
直接分配值:(不良做法)
public class Rainfall {
private int[][] rain = new int[4][7];
private int[] average = new int[4];
private int[] sum = new int[4];
public Rainfall(){
}
}
为构造函数中的字段指定值:
public class Rainfall {
private int[][] rain;
private int[] average;
private int[] sum;
public Rainfall(){
rain = new int[4][7];
average = new int[4];
sum = new int[4];
}
}