搜索列表

时间:2014-03-12 02:47:31

标签: java arrays

没关系,我想通了:

public class AnimalSearch
{
    public static void main(String[] args)

    }
}

2 个答案:

答案 0 :(得分:6)

您正在将整个数组A与字符串进行比较。

尝试比较各个元素。

if (A[compCount -1].equals(animal)) {
  System.out.println("String " + animal + " was found using " + compCount + " comparisions.");
  break;
 }

另请注意,打印后应break

最好还是使用equalsIgnoreCase

答案 1 :(得分:0)

试试这个,

String[] A = {"cat", "dog", "mouse", "fox", "bear", "wolf", "eagle", "moose", "parrot", "rabbit"};
String animal = (args[0]);

if(Arrays.asList(A).contains(animal))
   {
      System.out.println(" String " + animal + " was found using " + compCount + " comparisions. ");
   }
   else
   {
      System.out.println(" String " + animal + " could not be found, and " + compCount + " comparisons were performed. ");
   }