如何在方法中添加数组元素?

时间:2016-04-07 23:37:47

标签: java arrays sum

我必须输入三个数组元素然后一个方法应该计算它们并返回答案。我只有这个:

boolean answer = false;   

final int ARRAY_SIZE = 3;
 int sum[] = new int [ARRAY_SIZE];

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

 sum[i]= Integer.parseInt(JOptionPane.showInputDialog("Please enter a number"));    

 }

 answer = one(sum);

 JOptionPane.showMessageDialog(null,"The sum of the elements is "+answer);
}  
public static boolean one(int[] nums){return(nums[0] + nums[1] + nums[2]);}

}   

2 个答案:

答案 0 :(得分:2)

目前,您从boolean方法返回one。您应该返回int

答案 1 :(得分:1)

也许我的改进会对你有所帮助:

public static void main(String[] args) {
    final int ARRAY_SIZE = 3;
    int sum[] = new int[ARRAY_SIZE];
    for (int i = 0; i < sum.length; i++) {

        sum[i] = Integer.parseInt(JOptionPane.showInputDialog("Please enter a number"));

    }
    JOptionPane.showMessageDialog(null, "The sum of the elements is " + one(sum));
}

public static int one(int[] nums) {
    return (nums[0] + nums[1] + nums[2]);
}