简体   繁体   English

如何在没有 ArrayIndexOutOfBoundsException 的情况下添加到数组?

[英]How to add to array without ArrayIndexOutOfBoundsException?

Can anyone answer this question?有人能回答这个问题吗?

public class AddingArray {
  public static void main(String[] args){
      int arry1[] = {2,3,4,5,6,7,9};
      int arry2[] = {4,3,7,9,3,5};

      for(int i = 0; i <arry1.length; i++){
          int result = arry1[i] + arry2[i];
          System.out.println("Result "+result);
      }
   }
}

Whenever I try executing the above code I get the error Exception in每当我尝试执行上述代码时,我都会收到错误异常

thread "main" java.lang.ArrayIndexOutOfBoundsException: 6   at
basics.AddingArray.main(AddingArray.java:9)

But,my output should be like this 6,6,11,14,9,12,9但是,我的输出应该是这样的 6,6,11,14,9,12,9

It is because your loop will go from 0 to 6 (which is the array1.length - 1 ) and your array2 only has 6 elements (so from 0 to 5 ).这是因为您的循环将从 0 到 6(即array1.length - 1 ),而您的array2只有 6 个元素(所以从05 )。

So when you are accessing arry2[6];所以当你访问arry2[6]; It will give you the java.lang.ArrayIndexOutOfBoundsException .它会给你java.lang.ArrayIndexOutOfBoundsException

You could change your for loop to go to the length of the smallest array:您可以更改 for 循环以转到最小数组的长度:

for(int i = 0; i < arry2.length; i++){ /*Do what you want */ }

Or add an element in array2 , but that is yours to decide since I do not know your requirements.或者在array2添加一个元素,但这是你的决定,因为我不知道你的要求。

As people have mentioned, one of yours arrays is literally shorter than the other.正如人们所提到的,你的一个数组实际上比另一个短。 Take two blocks and overlay them over only one block.取两个块并将它们覆盖在一个块上。 The second (in this case index 1 block) would fall into the abyss, because the block that was supposed to catch it never existed.第二个(在这种情况下索引 1 块)将掉入深渊,因为本应捕获它的块从未存在过。

I would make sure both of them are of the same size.我会确保它们的大小相同。 If you do want to leave em as they are, I would do this:如果您确实想让它们保持原样,我会这样做:

int result = 0;

try
{
   for(int i = 0, length = array2.length; i < length; i++)
   {

      result = array1[i] + array2[i];
      System.out.println("Result is: " + result);

    }
    catch(Exception e)
    {
       System.out.println("You tried to do something that resulted in an error");
       System.out.println("Your previous result was: " + result);
    }
 }

SO, assuming that I still recall how to do basic arrays, what this code will do is that it will catch any errors thrown by your code.所以,假设我还记得如何做基本数组,这段代码会做的是它会捕获你的代码抛出的任何错误。

Let's make this as simple and understandable as possible, with no fancy annotations:让我们尽可能简单易懂,没有花哨的注释:

  1. You have two int arrays, of not equal lengths, and you wish to add the index-paired numbers to an array of the sums.您有两个长度不等的 int 数组,并且您希望将索引配对的数字添加到总和数组中。 However, if one of the arrays does not have any more numbers, the value of the longest array will be the result.但是,如果其中一个数组没有更多数字,则最长数组的值将作为结果。

     public class AddingArray { public static void main(String[] args){ int arry1[]={2,3,4,5,6,7,9}; int arry2[]={4,3,7,9,3,5};

You need to determine the length of the longest array.您需要确定最长数组的长度。 You can do this with a Math.max() -method, where you give the length of each array as parameters:您可以使用Math.max()方法来执行此操作,您可以在其中将每个数组的长度作为参数:

      int biggestArrayLength = Math.max(arry1.length, arry2.length);

Then, instead of for(int i=0;i<arry1.length;i++){ , you write:然后,而不是for(int i=0;i<arry1.length;i++){ ,你写:

      for(int i=0;i<biggestArrayLength;i++){

Now it doesn't matter which of the two arrays is the biggest one.现在,两个数组中哪一个最大并不重要。

Inside the loop, I would define two ints, representing a value from each of the two arrays:在循环内部,我将定义两个整数,代表来自两个数组中的每一个的值:

      int value1 = arry1[i];
      int value2 = arry2[i];

however, this will give an error when the smallest array does not have any more elements.但是,当最小的数组没有更多元素时,这将产生错误。 We need to check if the array actually has an element with index i.我们需要检查数组是否真的有一个索引为 i 的元素。 index numbers in arrays start with 0. so if the length is 7, the 7 elements will have index numbers from 0-6.数组中的索引号从 0 开始。因此,如果长度为 7,则 7 个元素的索引号为 0-6。 In other words, only index numbers that are lower (and not equal) to length, is valid numbers:换句话说,只有小于(且不等于)长度的索引号才是有效数字:

      int value1 = 0;
      int value2 = 0;

      if(arry1.length > i){
          value1 = arry1[i];
      }
      if(arry2.length > i){
          value2 = arry2[i];
      }

      int result = value1 + value2;
      System.out.println("Result "+result);
  }

} } } }

Now, if you need to put these in a third array, say named sumArray, this would be the complete code:现在,如果您需要将这些放在第三个数组中,比如名为 sumArray,这将是完整的代码:

public class AddingArray {
  public static void main(String[] args){
      int arry1[]={2,3,4,5,6,7,9};
      int arry2[]={4,3,7,9,3,5};

      int biggestArrayLength = Math.max(arry1.length, arry2.length);

      int[] sumArray = new int[biggestArrayLength];
      for(int i=0;i<biggestArrayLength;i++){

          int value1 = 0;
          int value2 = 0;
          if(arry1.length > i){
              value1 = arry1[i];
          }
          if(arry2.length > i){
              value2 = arry2[i];
          }

          int result = value1 + value2;
          sumArray[i] = result;
          System.out.println("Result "+result);
      }
   }
}

Because arry1 is longer than arry2 when you make the last iteration through the loop arry2[i] returns null because there is no element to return.因为当您通过循环进行最后一次迭代时, arry1arry2arry2[i]返回 null,因为没有要返回的元素。 either do: if(arry2[i] != null) { //run your adding code } or change your arrays to be the same size要么做: if(arry2[i] != null) { //run your adding code }或将数组更改为相同大小

Edit: The reason it is not working properly is because you are using the length of the largest array as the conditional within the for loop.编辑:它无法正常工作的原因是因为您使用最大数组的长度作为 for 循环中的条件。 This condition allows you to attempt to access the 2nd array at a location that does not exist, which is why you are getting an ArrayIndexOutOfBoundsException .此条件允许您尝试在不存在的位置访问第二个数组,这就是您收到ArrayIndexOutOfBoundsException

Can we stop the downvoting?我们可以停止投票吗?

End edit----结束编辑----

If you want to add up all of the elements in the array use this code.如果要将数组中的所有元素相加,请使用此代码。

    public class AddingArray {
      public static void main(String[] args){
          int arry1[]={2,3,4,5,6,7,9};
          int arry2[]={4,3,7,9,3,5};
          int result = 0;

          for(int i=0;i<arry1.length;i++){
              result+=arry1[i];
          }
          for(int j=0; j < array2.length; j++){
              result += array2[j];
          }

          System.out.println("Result: "+ result);
      }
}

if you are trying to sum individual elements as you loop you can do the following.如果您尝试在循环时对单个元素求和,则可以执行以下操作。 This will properly handle 2 arrays of different length regardless of which one is longer.这将正确处理 2 个不同长度的数组,而不管哪个数组更长。

    public class AddingArray {
      public static void main(String[] args){
          int arry1[]={2,3,4,5,6,7,9};
          int arry2[]={4,3,7,9,3,5};
          int result = 0;
          for(int i=0;i<arry1.length;i++){
              result=arry1[i];
              if(i < array2.length){
                 result += array2[i];
              }
              System.out.println("Result: "+ result);
          }
          for(int j = i; j < array2.length; j++){
              System.out.println("Result: "+ array2[j]);
          }

      }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从数组中删除元素而不获取:ArrayIndexOutOfBoundsException? - How do I remove an element from an array without getting: ArrayIndexOutOfBoundsException? 填充链接列表数组而没有得到:ArrayIndexOutOfBoundsException - Filling an array of linked lists without getting an: ArrayIndexOutOfBoundsException 如何在没有 ArrayIndexOutOfBoundsException 的情况下通过 executeBatch 获取生成的键? - How to get generated keys by executeBatch without ArrayIndexOutOfBoundsException? 如何修复二维数组的ArrayIndexOutOfBoundsException - How to fix ArrayIndexOutOfBoundsException for a two dimensional array 需要处理堆栈数组的ArrayIndexOutOfBoundsException,而无需结束程序 - Need to handle ArrayIndexOutOfBoundsException for stack array, without program ending 如何在不使用 try-catch 的情况下解决 ArrayIndexOutOfBoundsException? - How to address ArrayIndexOutOfBoundsException without using try-catch? ArrayIndexOutOfBoundsException ArrayLists的数组 - ArrayIndexOutOfBoundsException Array of ArrayLists 二维数组的ArrayIndexOutOfBoundsException - ArrayIndexOutOfBoundsException for a 2D array Array.length &amp; ArrayIndexOutOfBoundsException - Array.length & ArrayIndexOutOfBoundsException 多维数组中的ArrayIndexOutOfBoundsException - ArrayIndexOutOfBoundsException in multi dimentional array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM