Java阵列加1

时间:2018-10-04 02:17:35

标签: java arrays

我的Java代码需要加1,并且我收到一条错误消息

ArrayTask3.java:8: error: incompatible types: int cannot be converted to int[]
     int[] row = intList [i];

它应该只读取我的数组,然后向每个数字加1。有人可以帮我让它正常工作。

class ArrayTask3 {

   public static void main(String[] args) {
      int [] intList = {5,20,32,7,9};
      int sum = 0;

      for (int i = intList.length-1; i >=0; i--) {
         int[] row = intList [i];
         for (int j = 0; j < row.length; j++) {
            row[j] = row[j] + 1;
         }

         System.out.println ("intList [" + i + "]: " + intList [i]);
      }
      for (int counter=0;counter<intList.length;counter++)
         sum = sum + intList[counter];
      System.out.println ("Sum = " + sum);
   }    
}    

5 个答案:

答案 0 :(得分:0)

这里的问题是您要设置一个与int相等的int数组(而不是与int相等的数组元素)。我为您修复了代码:

class ArrayTask3 {
       public static void main(String[] args) {
          int [] intList = {5,20,32,7,9};
          int sum = 0;

          for (int i = intList.length-1; i >=0; i--) {

            // you can directly set the element using this
            intList[i] = intList[i]+1;

             System.out.println ("intList [" + i + "]: " + intList [i]);
          }
          for (int counter=0;counter<intList.length;counter++)
             sum = sum + intList[counter];
          System.out.println ("Sum = " + sum);
       }    
}

答案 1 :(得分:0)

intList只是int[],而不是二维数组。只需在intList[i]++中进行操作,而不必在for循环中创建一个名为“ row”的新数组。

({intList[i]++intList[i] = intList[i] + 1intList[i] += 1相同

for (int i = 0; i < intList.length; i++) {
    intList[i]++;
    System.out.println ("intList [" + i + "]: " + intList [i]);
}

此外,让您的for循环更正常

for (int i = 0; i < someArray.length; i++) {
    //code
}

不是您所做的,而是

for (int i = someArray.length-1; i >= 0; i--) {
    //code
}

这两个功能完全相同,但是第一个选项更“正常”并且更易于阅读。

答案 2 :(得分:0)

public Range of(Double point){ return function.of(new Domain(point)); } 是一维数组,因此intListintList[i]int位置的i。我认为您想要做的是将整数增加1或intListintList[i]++;

您当前正在尝试通过选择行来遍历二维数组或矩阵。在这种情况下,您需要将intList[i] += 1;定义为intList或整数数组的数组。

答案 3 :(得分:0)

      for (int i = intList.length-1; i >=0; i--) {
         /**
          *  I am not sure on what you want to do with this line.
          *  You can't assign an integer to array without reference
          *  If you want to copy the value of intList to row you can use int[] row = intList;
          */
         int[] row = intList [i];

         for (int j = 0; j < row.length; j++) {
           row[j] = row[j] + 1;
         }

        System.out.println ("intList [" + i + "]: " + intList [i]);
    }

答案 4 :(得分:0)

尝试使用以下代码。将每个数字加1,并在最后打印所有数字的总和。

public static void main(String[] args) {
  int[] intList = { 5, 20, 32, 7, 9 };
  int sum = 0;
  for (int i = 0; i < intList.length; i++) {
    intList[i]++;
    System.out.println("intList [" + i + "]: " + intList[i]);
    sum += intList[i];
  }
  System.out.println(sum);
}