【问题标题】:getting the position of an Item using indexOf method使用 indexOf 方法获取 Item 的位置
【发布时间】:2013-11-05 05:58:09
【问题描述】:

getPosition 方法使用 ArrayLinearList 类中的 indexOf 方法返回列表中项目的位置,每当我传递一个字符串的参数时,即使该项目存在于列表中,它也始终返回 -1

  private ArrayLinearList array;
        private Scanner scanner;
        public ArrayShoppingList1()
        {
            array = new ArrayLinearList();
            scanner = new Scanner(System.in);    
        }


    public int getPosition()
        {

        System.out.println("Please enter the name of the Item");
        String name = scanner.nextLine();
        int z = array.indexOf(name);
        return z;

    }






/** @return index of first occurrence of theElement,
     * return -1 if theElement not in list */
   public int indexOf(Object theElement)
   {
      // search element[] for theElement
      for (int i = 0; i < size; i++)
         if (element[i].equals(theElement))
            return i;

      // theElement not found
      return -1;
   }   

【问题讨论】:

  • 使用instanceof检查Element参数。
  • 我们能看到 element[] 是什么吗?
  • 建议在indexOf() 的开头添加System.out.println(Arrays.toString(element)); 以仔细检查数组中的内容

标签: java object methods arraylist java.util.scanner


【解决方案1】:

请提供完整的代码。什么是element

对了,试试打印出name的值——如果你读到的第一行是空的怎么办?

【讨论】:

    【解决方案2】:

    您可能忘记将字符串存储到array

    array.add("some string here");
    

    或者,您确定要搜索的元素在数组中吗?

    尝试使用compareTo() 方法而不是equals 来比较字符串。

    【讨论】:

    • 我已经有另一种方法可以将字符串添加到数组中,如果您愿意,我可以为您提供该方法
    【解决方案3】:

    假设theElement 提供了一个字符串。

    public int indexOf(Object theElement)
       {
          String S = (String) theElement;
          // search element[] for theElement
          for (int i = 0; i < size; i++)
             if (element[i].equalsIgnoreCase(S))
                return i;
    
          // theElement not found
          return -1;
       }   
    

    【讨论】:

      【解决方案4】:

      在您的indexOf 函数中:

      public int indexOf(Object theElement)
         {
            // search element[] for theElement
            for (int i = 0; i < size; i++)
               if (element[i].equals(theElement))
                  return i;
      
            // theElement not found
            return -1;
         } 
      

      大小可能是&lt; 1; another case would be you are having大写字母and小写字母letter problem. Try comparing withString.equalsIgnoreCase(String)`函数

      【讨论】:

      • 假设使用element.length 是正确的。如果 element 是预分配的并且没有使用所有数组元素,则可能不是这样,因此 0 size element.length。不幸的是,我们不知道size 是什么或它是如何设置的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      相关资源
      最近更新 更多