weixin_46863753
weixin_46863753
2021-04-22 17:48
采纳率: 66.7%
浏览 24
已采纳

求问“在数组中判断元素是否存在并输出该位置时循环”出现微小错误该如何解决

程序要求在所输入的数组中查找后续输入元素是否存在其中,若存在输出该位置,若不存在输出-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);
  }
}

请各位大佬看看细节 谢谢大哥!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • qq_31283125
    --.. 2021-04-22 17:57
    已采纳

    字符串判断用equals

    点赞 评论

相关推荐