java - Finding the union of two arrays -
i'm trying find union of 2 arrays created user input. keep getting:
exception in thread "main" java.lang.arrayindexoutofboundsexception: 4 @ twosets.main(twosets.java:47)
import java.util.scanner; public class twosets { public static void main(string[] args) { int i, array, choice; scanner input = new scanner(system.in); system.out.print("how many numbers want in each set? "); array = input.nextint(); int set1[] = new int[array]; int set2[] = new int[array]; int set3[] = new int[array*2]; for(i=0;i<set1.length;i++) { system.out.print("enter number first set: "); set1[i] = input.nextint(); } system.out.print("\n"); for(i=0;i<set2.length;i++) { system.out.print("enter number second set: "); set2[i] = input.nextint(); } system.out.print("enter 1 find union\n" + "enter 2 find intersection\n" + "enter 3 find difference\n"); choice = input.nextint();
the code above initializing , getting user input, working fine. code below not functioning.
if(choice == 1) { for(i=0;i<array;i++) { set3[i] = set1[i]; } for(i=array;i<array*2;i++) { boolean check = union(set2[i], set3); if(check == false) { set3[i] = set2[i]; } } for(i=0;i<set3.length;i++) { system.out.print(set3[i]); } } } public static boolean union(int number, int[] array) { (int : array ) { if (i == number) { return true; } } return false; } }
the set2 have length of array, in:
for(i=array;i<array*2;i++) { boolean check = union(set2[i], set3); if(check == false) { set3[i] = set2[i]; } }
you use array*2 in loop. think bug.
Comments
Post a Comment