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

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

程序要求在所输入的数组中查找后续输入元素是否存在其中,若存在输出该位置,若不存在输出-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条回答 默认 最新

  • --.. 2021-04-22 17:57
    关注

    字符串判断用equals

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog