|
|
|||||||||
|
|||||||||
|
|||||||||
| |
|||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Java newbie help.
Hey, im in need of a little help with a little piece that i need to do and i dont especially get how to do it. What i want to do is write a method that takes two one-dimensional arrays of strings and determine whether or not both arrays contain the same words. For example, the following two arrays contain the same words:
cast static thread make void import void make import cast thread static Im struggling of how i would go about doing tis and if anyone has any ideas id be greatful. Cheers. |
|
#2
|
|||
|
|||
|
The answer seems to be to just iterate through each array, and compare all elements to each other.
For example (I know, ugly complexity, but it gets the job done): Code:
public void printDuplicates(String[] arr1, String[] arr2) {
for(int i = 0; i < arr1.length; i++) {
for(int j = 0; j < arr2.length; j++) {
/* remember to use the right indexer, or you will get an indexOutOfBounds exception */
if(arr1[i].equals(arr2[j])) {
System.out.println("Duplicate found: "+arr1[i]);
}
}
}
}
.
__________________
Benjamin Horsleben horsleben.com/benjamin Don't blame malice for what stupidity can explain |
|
#3
|
||||
|
||||
|
if you get that error just use...
try-catch to alter and keep going colton22 |
|
#4
|
|||
|
|||
|
Added a count to fizker's code to see if all the word on arr1 are on arr2:
Code:
public void printDuplicates(String[] arr1, String[] arr2) {
int count = 0;
for(int i = 0; i < arr1.length; i++) {
for(int j = 0; j < arr2.length; j++) {
/* remember to use the right indexer, or you will get an indexOutOfBounds exception */
if(arr1[i].equals(arr2[j])) {
System.out.println("Duplicate found: "+arr1[i]);
count++;
}// end if
}// end for
}// end for
if(count == arr1.length)
System.out.println("All words on array1 are on array2");
}
|
|
#5
|
|||
|
|||
|
to make the method more efficient, in terms of doing as little checking whenever possible, I'd approach it something like this...
Code:
public boolean matches(String[] arr1, String[] arr2) {
if (arr1.length == arr2.length) {
for (int i = 0; i < arr1.length; i++) {
boolean foundMatch = false;
for (int j = 0; j < arr2.length; j++) {
if (arr1[i].equals(arr2[j])) {
foundMatch = true;
break;
}
}
if (!foundMatch) {
return false;
}
}
return true;
}
return false;
}
|
![]() |
| Viewing: Dev Articles Community Forums > Programming > Java Development > Java newbie help. |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|