Can someone take a look at this. Create a method called findElement, which takes an integer value and a two-dimensional integer array as inputs and returns true if the value is in the array. If the value is not in the array, the method should return false.
This is what I have. Its not returing the correct answer.

``public boolean findElement(int value, int[][] theArray){``
``````int row = 0;
int col = 0;
for (row =0; row<theArray.length; row++){
for(col = 0; col<theArray[row].length; col++){
}
}
if (row == col)
return false;
else
return true;
}``````

Hint draw a flow chart.

``````int row = 0;
int col = 0;
for (row =0; row<theArray.length; row++)
{
for(col = 0; col<theArray[row].length; col++)
{
// no work being done here...
// you should compare theArray[row][col] with what you're
// searching for and you can return if it's a match
}
}
if (row == col) // row and col were the array indices, why compare them?
return false;
else
return true;``````

Thanks but I figured it out

``````boolean result = false;
int row = 0;
int col = 0;
for (row =0; row<theArray.length; row++){
for(col = 0; col<theArray[row].length; col++){
if (theArray[row][col]== value)
result = true;
}
}
return result;``````

hint: learn to indent your braces properly

Thanks but I figured it out

``````boolean result = false;
int row = 0;
int col = 0;
for (row =0; row<theArray.length; row++){
for(col = 0; col<theArray[row].length; col++){
if (theArray[row][col]== value)
result = true;
}
}
return result;``````

Perfect. I'll just suggest one change here, but it's probably something you don't need to worry about: if you have a huge array (say, something like theArray[1000][1000]) and the first item is a match, you'll still check all of the million things in the 2D array even though you've found a match. There's two easy ways to get out of this, and which to use is up to you (there's reasons for each). First, you can just return once you've found the match:

``````for(/*...*/){
for(/*...*/){
if(theArray[row][col] == value)
return true;  // gets out of the loops (and the function)
}
}
return false;``````

It should be fairly easy to see how this gets the right result and why it's more efficient. Another way to do it is a tad more jumbled and fancy, and involves labels (which can be a touchy subject). It looks something like this:

``````outerLoop:
for(/*...*/){
for(/*...*/){
if(theArray[row][col] == value){
result = true;   // same as yours
break outerLoop; // breaks the outer loop and goes to the return
}
}
}
return result;``````

Notice the `outerLoop:` before the first loop. As of Java 1.5, you can use labels like this to break or continue a specific loop instead of having these inefficiencies.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.