尝试对数组中的元素求和时的奇怪输出(使用方法)(weird output when trying to sum elements in array (using method))
我正在制作一个添加数组中所有元素的方法。 我从main中的testArray1获取数组。 输出是“[I @ 15d6c7”
public class arrayExercises{ public int ArraySum(int[] array){ int sum = 0; for(int i = 0; i < array.length; i++){ sum += array[i]; } return sum; } public static void main(String[] args){ int[] testArray1 = {1,2,3,4}; System.out.println(testArray1); } }I am making a method that adds all the elements in the array. I am getting the array from the testArray1 in main. The output is "[I@15d6c7"
public class arrayExercises{ public int ArraySum(int[] array){ int sum = 0; for(int i = 0; i < array.length; i++){ sum += array[i]; } return sum; } public static void main(String[] args){ int[] testArray1 = {1,2,3,4}; System.out.println(testArray1); } }最满意答案
您打印出testArray1的字符串表示形式而不是其元素的总和。 我想你想改变你的主要方法如下:
public static void main(String[] args){ int[] testArray1 = {1,2,3,4}; System.out.println(ArraySum(testArray1)); }You're printing out the string representation of testArray1 instead of the sum of its elements. I think that you want to change your main method as follows:
public static void main(String[] args){ int[] testArray1 = {1,2,3,4}; System.out.println(ArraySum(testArray1)); }更多推荐
发布评论