Java数组加1

我的 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);

   }    

}    


神不在的星期二
浏览 253回答 3
3回答

海绵宝宝撒

intList只是一个int[],而不是二维数组。无需在 for 循环中创建一个名为“row”的新数组,您只需执行intList[i]++.(intList[i]++和intList[i] = intList[i] + 1和intList[i] += 1是一样的)for (int i = 0; i < intList.length; i++) {&nbsp; &nbsp; intList[i]++;&nbsp; &nbsp; System.out.println ("intList [" + i + "]: " + intList [i]);}此外,让你的 for 循环更正常for (int i = 0; i < someArray.length; i++) {&nbsp; &nbsp; //code}而不是你所做的,这是for (int i = someArray.length-1; i >= 0; i--) {&nbsp; &nbsp; //code}两者都做完全相同的事情,但第一个选项更“正常”且更易于阅读。

守候你守候我

问题是您将 int 数组设置为等于 int (而不是等于 int 的数组元素)。我为您修复了代码:class ArrayTask3 {&nbsp; &nbsp; &nbsp; &nbsp;public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int [] intList = {5,20,32,7,9};&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int sum = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = intList.length-1; i >=0; i--) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // you can directly set the element using this&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; intList[i] = intList[i]+1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println ("intList [" + i + "]: " + intList [i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int counter=0;counter<intList.length;counter++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sum = sum + intList[counter];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println ("Sum = " + sum);&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;&nbsp;}

白猪掌柜的

intList是一维数组,intList[i]在 中的intat 位置i也是如此intList。我认为您想要做的是将整数增加一或intList[i]++;或intList[i] += 1;。您当前正在尝试通过选择行来遍历二维数组或矩阵。在这种情况下,您需要定义intList为一个int[][]或一个整数数组的数组。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java