I have done some code for a linear search. The code compiles fine but every time my output is given to -1 and data not found. Could someone please advise me on where i am going wrong:
import javax.swing.*;
public class Unit15Dem1
{
public static void main(String[] args)
{
final int ARRAY_SIZE = 4;
String[] a = new String[ARRAY_SIZE];
a[0]="dog";
a[1]="cat";
a[2]="mouse";
a[3]="pig";
int result;
String searchKey = JOptionPane.showInputDialog("Give me a name of an animal");
result = linearSearch(a, searchKey, ARRAY_SIZE);
if(result== -1){
JOptionPane.showMessageDialog(null,"KEY " + searchKey + " NOT FOUND");
}
else{
JOptionPane.showMessageDialog(null,"KEY " + searchKey + " FOUND in position " + result);
}
}
public static int linearSearch(String[] data, String key, int sizeOfArray)
{
for (int counter = 0; counter < sizeOfArray; counter++)
{
if (data[counter] == key)
return counter;
}
return -1;
}
}
//Soz had to squeeze everything in, ty
2007-12-21
03:42:50
·
2 answers
·
asked by
Anonymous
in
Computers & Internet
➔ Programming & Design