English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

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

2 answers

Try using the .equalsIgnoreCase(String) method rather than just checking to see if equal. I forget exactly where it is documented, but you can't just use the == where you are using it.

2007-12-21 03:55:26 · answer #1 · answered by Jim Maryland 7 · 0 0

public static int linearSearch(String[] data, String key, int sizeOfArray)
{
for (int counter = 0; counter < sizeOfArray; counter++)
{
if (data[counter].equals(key))
return counter;
}
return -1;
}

2007-12-21 12:00:01 · answer #2 · answered by bob j 4 · 0 0

fedest.com, questions and answers