程序要求在所输入的数组中查找后续输入元素是否存在其中,若存在输出该位置,若不存在输出-1.
方法CreateArray用于创建数组,方法SearchArray用于查找数组并输出,问题出在似乎查找方法中循环出错,无论元素是否存在均输出不存在。
以下为编写代码段:
import javax.swing.JOptionPane;
class LinearSearch
{
//a method which creates the array of artists
public static String[]CreateArray()
{
String array[] = new String[5];
String Artist;
// declare local variables
for(int counter = 0;counter<array.length;counter++)
{
Artist = JOptionPane.showInputDialog("please enter the artistslist");
array[counter] = Artist;
//store in array
}
//end the loop
return array;
}
//end the method to CreateArray
//a method which search the entervalute in the array of artists
public static int SearchArray(String[] array2, String targetValue)
{
for (int i = 0; i < array2.length; i++)
{
if (array2[i] == targetValue)
{
return i;
}
}
//end the loop
return -1;
}
//end the method to SearchArray
public static void main(String[] args)
{
String Favourite;
Favourite = JOptionPane.showInputDialog("please enter your favourite artist");
// declare local variables
String[] Artists = CreateArray();
int Index=SearchArray(Artists,Favourite);
JOptionPane.showMessageDialog(null,"The address of artist"+Favourite+"is"+Index,"The Result",JOptionPane.PLAIN_MESSAGE);
}
}
请各位大佬看看细节 谢谢大哥!