【问题标题】:Binary Search String Array, returns -1二进制搜索字符串数组,返回 -1
【发布时间】:2016-03-12 07:14:47
【问题描述】:

数组已经排序了。

然后我要求用户输入一个名称,以便可以在数组“names”中搜索它。这样做的目的是让我可以获取名称的索引,以便我可以从二维数组“scores”中输出相应的分数。

这些是我的数组:

String[] names = new String[10];
int[][] scores = new int[10][3];

这是二分搜索:

System.out.println("Which student's scores do you want to see?");

    String name = scnr.nextLine();
    scnr.nextLine();

    int index = Arrays.binarySearch(names, name);

    System.out.println(index);

我打印索引只是为了检查它是否正确,但我看到它打印出 -1。我输入正确,没有空格并且大写正确。我不确定我做错了什么。

这是我的代码:

import java.util.Scanner;
import java.util.Arrays;

/**
*Write a program that will input 10 students names
* in random order and their corresponding 3 project scores.
* Data will be read into 2 separate arrays: an array of strings
* for the names and a 2D array for the scores.
* Output input data in table form
*Using Binary Search your program will accept user input (name) and output  
*the name and its corresponding 3 project scores.
*For each of the 3 projects, output the name of the student(s) who scored
the highest mark.
**/

class NameAndGrades {
    public static void main(String[] args) {
        //Scanner object to allow user input
        Scanner scnr = new Scanner(System.in);

        //This array will store the names of the students
         String[] names = new String[10];

    //This 2D array will store the 3 project scores
    int[][] scores = new int[10][3];


    //Ask user to input the student names
    System.out.println("Enter the 10 student names: ");

    for (int index = 0; index < 10; index++) {
        System.out.print("Student " + (index + 1) + ": ");
        names[index] = scnr.nextLine();
    }


    //Ask user to enter the corresponding project scores

    System.out.println("\nEnter the 3 project grades for each student:\n");

    for(int i = 0; i < names.length; ++i)
    {
     System.out.print("   Enter three project grades for " + names[i] + " :   ");
     scores[i][0] = scnr.nextInt();
     scores[i][1] = scnr.nextInt();
     scores[i][2] = scnr.nextInt();
     }



    System.out.println("Which student's scores do you want to see?");
    String name = scnr.nextLine();
    scnr.nextLine();

    int index = Arrays.binarySearch(names, name);

    System.out.println(index);
}



/**Selection sort method made to sort the student names in
* alphabetical order.
@param names names of students
@return the names organized alphabetically
*/

public static String[] selectionSort(String[] names) {
    for (int index = 0; index < names.length - 1; ++index) {
        int minIndex = index;
        for (int j = index + 1; j < names.length; ++j) {
            if (names[j].compareTo(names[minIndex]) < 0) {
                minIndex = j;
            }
        }
        String temp = names[index];
        names[index] = names[minIndex];
        names[minIndex] = temp;
    }
    return (names);
}

以下只是一个可能的选择,我的主要问题是为什么我的索引为 -1

除非我可以使用这样的东西进行二分搜索,否则我会从我的书中得到这个示例(但我需要帮助对其进行更改,以便它可以用于字符串数组):

public static int binarySearch(String[] names, String name)
{
  int first = 0;
  int last = names.length - 1;
  int mid;
  int position = -1;
  boolean found = false;

  while(!found && first <= last)
  {
    mid = (first + last)/2;
    if (names[mid] == name)
    {
      found = true;
      position = mid;
    }
    else if (names[mid] > name)
      last = mid - 1;
    else
      first = mid - 1;
  }
  return position;
}

【问题讨论】:

  • 请展示一个简短但完整的程序(包括示例数据),而不仅仅是一些零碎的程序——它会让帮助你变得更加容易。见minimal reproducible example
  • 虽然至少有一个错误:first = mid - 1; 应该是first = mid + 1;
  • @JonSkeet 会的,对不起!
  • binarySearch 中的第二个错误:“names[mid] == name”没有按照您的想法执行。您需要使用类似“names[mid].equalsIgnoreCase”(name)" 的内容。请查看stackoverflow.com/a/513839/509840 了解为什么会这样。
  • 您是否在 IDE 调试器中单步执行了代码?这就是开始的地方。

标签: java arrays string binary-search


【解决方案1】:

为什么要使用原始数组?您应该改为使用从学生姓名到学生分数的映射。然后,您可以使用 API 调用轻松找到它们。例如:

Map<String, List<Integer>> studentMarks = new HashMap(10);
String targetStudent;

//... perform initialization here

System.out.println(studentMarks.get(targetStudent));

【讨论】:

  • 对不起,我应该早点说,但我正在使用我学到的东西。我不知道地图,没有被教过。到目前为止,我只知道原始数组。
  • 这不是 OP 问题的答案。
  • 嗯,好的。所以你不是试图解决一个特定的问题,而是为一些家庭作业实现一个低级算法。对不起,如果我误解了。
猜你喜欢
  • 1970-01-01
  • 2023-03-24
  • 2017-01-26
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
相关资源
最近更新 更多