无法修复arrayoutof bound exception

时间:2017-03-19 18:30:24

标签: java

我收到这些错误,这是一个运行时错误;我不知道为什么会发生这种情况我试图找到解决方案但却无法找到它。 由于我是java新手,请帮我找

  

线程中的异常" main" java.lang.ArrayIndexOutOfBoundsException:34       在UnionAndIntersection.BinarySearch(UnionAndIntersection.java:90)       在UnionAndIntersection.BinarySearch(UnionAndIntersection.java:96)       在UnionAndIntersection.BinarySearch(UnionAndIntersection.java:100)       在UnionAndIntersection.BinarySearch(UnionAndIntersection.java:100)       在UnionAndIntersection.BinarySearch(UnionAndIntersection.java:100)       在UnionAndIntersection.BinarySearch(UnionAndIntersection.java:100)       在UnionAndIntersection.Union(UnionAndIntersection.java:53)       在UnionAndIntersection.main(UnionAndIntersection.java:26)

请帮我解决这个问题

import java.util.Scanner;
import java.util.Arrays;

class UnionAndIntersection {
    public static void main(String args[]) throws Exception {
        int arr1[]=new int[20];
        int arr2[]=new int[20];
        int m,n,i,j;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter no of elements in first array");
        m=sc.nextInt();
        System.out.println("Enter no of element of second Array");
        n=sc.nextInt();
        System.out.println("Enter Elements in 1st Array");

        for(i=0;i<m;i++) {
            arr1[i]=sc.nextInt();
        }

        System.out.println("Enter Elements in 2nd Array");
        for(j=0;j<n;j++) {
            arr2[j]=sc.nextInt();
        }

        UnionAndIntersection ui=new UnionAndIntersection();
        ui.Union(arr1,arr2,m,n);
        ui.Intersection(arr1,arr2,m,n);
    }

    void Union(int arr1[],int arr2[],int m,int n) {
        if(m>n) {
            int tempa[]=arr1;
            arr1=arr2;
            arr2=tempa;

            int temp=m;
            m=n;
            n=temp;
        }

   Arrays.sort(arr1);
   for(int i=0;i<m;i++)
  {
    System.out.println(arr1[i]+"");
  }

  for(int i=0;i<2;i++)
   {
    if(BinarySearch(arr1,0,m-1,arr2[i])== -1)
        System.out.println(arr2[i]+"");
   }
   }
  void Intersection(int arr1[],int arr2[],int m,int n)
     {
   if(m>n)
   {
    int tempa[]=arr1;
    arr1=arr2;
    arr2=tempa;

    int temp=m;
    m=n;
    n=temp;

   }


    Arrays.sort(arr1);
    for(int i=0;i<m;i++)
   {
    System.out.println(arr1[i]+"");
   }

    for(int i=0;i<2;i++)
    {
    if(BinarySearch(arr1,0,m-1,arr2[i])!= -1)
        System.out.println(arr2[i]+"");
   }
   }
   int BinarySearch(int arr[],int l,int h,int x)
   {
    if(h>=1)
    {
        int mid=l+h-1/2;
        if(arr[mid]==x)
        {
            return mid;
        }
        else if(arr[mid]>x)
        {
            return BinarySearch(arr,l,mid-1,x);
        }
        else{

        return BinarySearch(arr,mid+1,h,x);
        }
    }
    return -1;
  }

 }  

1 个答案:

答案 0 :(得分:1)

您可以将数组的大小设置为20,而不是用户输入。如果用户输入的数字大于20,则会出现错误。 所以改变:

int arr1[]=new int[20];
int arr2[]=new int[20];

   int arr1[]=new int[m];
    int arr2[]=new int[n];