java - 如何找到小于另一个元素的元素?

标签 java eclipse string conditional-statements

我正在尝试建立一个使用字符串而不是整数的二分搜索程序。问题是我不知道如何创建小于字符串值的数字数组。

例如

字符串数组小于字符串值。

/**
   The StringBinarySearcher class provides a public static
   method for performing a binary search on an String array.
*/



public class StringBinarySearcher
{
   /**
      The search method performs a binary search on an String
      array. The array is searched for the number passed to
      value. If the number is found, its array subscript is
      returned. Otherwise, -1 is returned indicating the
      value was not found in the array.
      @param numbers The array to search.
      @param value The value to search for.
   */



   public static int search(String[] numbers, String value)
   {
      int first;       // First array element
      int last;        // Last array element
      int middle;      // Mid point of search
      int position;    // Position of search value
      boolean found;   // Flag

      // Set the inital values.
      first = 0;
      last = numbers.length - 1;
      position = -1;
      found = false;

      // Search for the value.
      while (!found && first <= last)
      {
         // Calculate mid point
         middle = (first + last) / 2;

         // If value is found at midpoint...
         if (numbers[middle] == value)
         {
            found = true;
            position = middle;
         }

         // else if value is in lower half...
         // needs array to be less then the string value?, without using equality regulators
         else if (numbers[middle].compareTo(numbers[middle +1]) > 0)
            last = middle - 1;
         // else if value is in upper half....
         else
            first = middle + 1;
      }

      // Return the position of the item, or -1
      // if it was not found.
      return position;
   }
}

最佳答案

你的问题是比较运算符(==)。比较运算符仅针对 Java 中的原始数据类型进行了明确定义。 String 是一个类(不是原始数据类型)。因此,您需要使用 String 的 equals(String) 方法来比较它们。

如果您想将它们作为数字进行比较,那么您需要将它们解析为整数。为此,您可以使用 Integer.parseInt(String) 然后比较整数。

关于java - 如何找到小于另一个元素的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5333863/

相关文章:

java - 如何将具有多种类型的中型数据集建模为一个类

java - 使用表单上的复选框输入将表单数据发送到不同的电子邮件地址

eclipse - CVS 存储库缺少连接类型

c - 如何限制用户输入字符串的大小或动态分配内存

c++ - 将 BSTR 复制到 char[1024]?

java - Auth.net Java SDK 中 com.auth.net.commons.authorize.net.GetSettledBatchList.main 线程 "main"java.lang.NullPointerException 中出现异常

java - 基于前提条件创建新实例的最佳方法

java - Eclipse 中的链接项目/文件夹不会部署在 tomcat 中

java - Maven war 插件 - 包括 WAR 中的其他文件

java - 返回 s 中的大写字母,如果没有找到则返回 -1