java - Comparing Arrays for common integer -
newbie here , new java itself. working on little project , stumped at. code has 2 arrays, passes these arrays down method. @ point method supposed , compare arrays, find highest common int in case program 10, program take 10 , return main printed out, program assuming possible there no common number in case print out -1. here code far.
public class arraycompare { public static void main(string [] args) { int [] arraya = {2, 4, 6 , 8, 10, 12}; int [] arrayb = {3, 4, 7 , 10, 11,13}; int result = largestincommon(arraya , arrayb); } public static int largestincommon( int [] a, int[] b) { int counter = 0; for( int x = 0; x < a.length; x++) { if(a[0]==b[x]) { for(int y = 0; y < b.length; y++) } } } }
loop on elements of 2 arrays. check if every element equals other , higher last higher element. if is, new higher element
int[] arraya = { 2, 4, 6, 8, 10, 12 }; int[] arrayb = { 3, 4, 7, 10, 11, 13 }; int higher = -1; (int = 0; < arraya.length; a++) { (int b = 0; b < arrayb.length; b++) { if (arraya[a] == arrayb[b] && arraya[a] > higher) { higher = arraya[a]; } } } system.out.println(higher);
output:
10
your error compare element before entering second loop. check if first element of arraya[]
exists in arrayb[]
, never set , return new higher value
Comments
Post a Comment