-1

The array's already sorted.

Then I ask the user to input a name so that it can be searched in the array "names". The purpose of this is so I can get the index of the name so i can output the corresponding scores from 2D array "scores".

these are my arrays:

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

and here's the binary search:

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);

I print the index just to check if it's correct, but I see it prints out -1. I am typing the input correctly, no white spaces and capitalized correctly. I'm not sure what I'm doing wrong.

Here's my code:

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);
}

THE BELOW IS JUST A POSSIBLE ALTERNATIVE, MY MAIN QUESTION IS WHY AM I GETTING AN INDEX OF -1

Unless I can use something like this for the binary search, I got this example off of my book (but i need help changing it so that it can work for String arrays):

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;
}
egg
  • 9
  • 5
  • Please show a short but *complete* program (including sample data) rather than just bits and pieces - it'll make it much, much easier to help you. See [mcve]. – Jon Skeet Mar 11 '16 at 22:49
  • Although at least one bug: `first = mid - 1;` should be `first = mid + 1;` – Jon Skeet Mar 11 '16 at 22:49
  • @JonSkeet Will do, sorry for that! – egg Mar 11 '16 at 22:50
  • @JonSkeet oh thank you! Copied it wrong – egg Mar 11 '16 at 23:02
  • 1
    Second bug in binarySearch: "names[mid] == name" doesn't do what you think it does. You need to have something like "names[mid].equalsIgnoreCase"(name)" instead. Please take a look at http://stackoverflow.com/a/513839/509840 for why this is so. – rajah9 Mar 11 '16 at 23:03
  • @rajah9 and for the "names[mid] > name" should it be changed to "names[mid].compareToIgnoreCase(name)" ? Thank you! – egg Mar 11 '16 at 23:08
  • _"i need help changing it so that it can work for String arrays"_ -- Sorry, this is not how StackOverflow works. Please visit the [help] and read [ask] for details. – Jim Garrison Mar 11 '16 at 23:08
  • @JimGarrison that wasn't really my main question. My main question is why am I getting -1 as my index. That second part is just a possible alternative to my problem. I'll edit my post then. – egg Mar 11 '16 at 23:12
  • 1
    Have you stepped through your code in your IDE debugger? That is the place to start. – Jim Garrison Mar 11 '16 at 23:14
  • Yes, if you're comparing one string to another, then compareToIgnoreCase will return "a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations." Please see the documentation at https://docs.oracle.com/javase/7/docs/api/java/lang/String.html – rajah9 Mar 12 '16 at 00:55

1 Answers1

0

Why are you using primitive arrays? You should instead use a Map from student name to student scores. You can then find them easily using API calls. For example:

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

//... perform initialization here

System.out.println(studentMarks.get(targetStudent));
Sina Madani
  • 1,246
  • 3
  • 15
  • 27
  • Sorry I should've said this earlier, but I'm using what I've learned. I don't know Map, haven't be taught about it. Primitive arrays is all I know so far. – egg Mar 11 '16 at 23:01
  • It's not the answer for the OP's question. – Edgar Rokjān Mar 11 '16 at 23:02
  • Ah ok. So you're not trying to solve a particular problem, but to implement a low-level algorithm for some homework. Sorry if I misunderstood. – Sina Madani Mar 11 '16 at 23:14