如何将数组索引为1而不是0?

use*_*386 4 java arrays indexing

在这种情况下,程序应该将所有数组添加到一起.但是如果我在sum方法参数中输入1,它将从7开始计数,但如果我输入0则输出0.

public class sList {

   public static void main(String[]args) {
       int[] array = {10,7,11,5,13,8}; // How do I make it read the value 10 as 1 in the array?
       sum(array.length,array);
   }

   public static int sum(int n, int[] S) {
       int i;
       int result;

       result = 0;
       for(i=1;i<=n;i++)
           result = result + S[i];

       System.out.println(result);
       return result;
   }    
}
Run Code Online (Sandbox Code Playgroud)

Boh*_*ian 8

我不会通过这个长度,因为:

  • 它是多余的 - array.length告诉你长度,如果你想知道它
  • 你无论如何都不需要知道长度,因为有一种更好的方法来迭代数组

相反,只需使用foreach循环遍历传入的整个数组:

public static int sum(int[] array) {
    int result = 0;
    for (int i : array)
        result += i;
    return result;
}
Run Code Online (Sandbox Code Playgroud)

这样做会导致代码更少,反过来也更容易阅读和理解.