Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Derek Derek
8,744 Pointsjava finding matching numbers algorithm between two sorted arrays
Hi! I am trying to write a java code that given two sorted arrays, looks for matching numbers. However, I am getting errors and cannot identify what error it is, but I think there is an error in every iteration of my loops.
Here's what I have:
import java.util.ArrayList;
public class MatchingNumbers {
private final int[] mArray1 = [13, 27, 35, 40, 49, 55, 59];
private final int[] mArray2 = [17, 35, 39, 40, 55, 58, 60];
public static void main(String[] args) {
find(mArray1, mArray2);
}
public static void find(int[] s1, int[] s2) {
List<Integer> storage = new ArrayList<Integer>();
for (int i = 0; i <= s1.length; i++) {
for (int j = 0; j <= s2.length; j++) {
if (s2[j] == s1[i]) {
storage.add(s2[j]);
break;
}
}
break;
}
System.out.println(storage);
}
}
I'd appreciate any help!!!
2 Answers
Ken Alger
Treehouse TeacherHyun;
Would something like this work for you?
import java.util.ArrayList;
import java.util.List;
class Main {
private static final int[] mArray1 = {13, 27, 35, 40, 49, 55, 59};
private static final int[] mArray2 = {17, 35, 39, 40, 55, 58, 60};
public static void main(String[] args) {
System.out.println("Matching Numbers");
System.out.println("Length of Array1: " + mArray1.length); // For debugging purposes
System.out.println("Length of Array2: " + mArray2.length); // For debugging purposes
find(mArray1, mArray2);
}
public static void find(int[] s1, int[] s2) {
List<Integer> storage = new ArrayList<Integer>();
for (int i = 0; i <= s1.length-1; i++) {
for (int j = 0; j <= s2.length-1; j++) {
if (s2[j] == s1[i]) {
storage.add(s2[j]);
System.out.println(storage); // For debugging purposes
continue;
}
}
continue;
}
System.out.println(storage);
}
}
Post back with questions.
Happy coding,
Ken
Ken Alger
Treehouse TeacherI would be pleased to take a whack at it, but you should probably start a new thread for your Python code. So as not to confuse folks with different languages in the same thread.
Derek Derek
8,744 PointsDerek Derek
8,744 PointsThank you so much!
Ken Alger
Treehouse TeacherKen Alger
Treehouse TeacherPleased it worked out.
Derek Derek
8,744 PointsDerek Derek
8,744 PointsKen Alger, I am also learning Python, and if you know Python, do you mind helping me out writing the above code in Python? This is what I have so far:
Thank you!