-1

Okay so here is my code.

import java.util.*;

//@Author: Tyler Cage
public class main {

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    String[] userID = new String[3];
    String[] password = new String[3];

    for ( int i = 0; i < userID.length; i++){
        System.out.print("User id at index #" + i + " ");
        userID[i] = scnr.next();
        System.out.print("Password at index #" + i + " ");
        password[i] = scnr.next();
    }

    System.out.print("Enter user id: ");
    String userIdInput = scnr.next();

    System.out.print("Enter password: ");
    String passwordInput = scnr.next();

    int x = Arrays.binarySearch(userID, userIdInput);
    int y = Arrays.binarySearch(password, passwordInput);

    if(x == y){
        System.out.println("Logged in!");
    }
    else{
        System.out.println("Invalid user id/password combo!");
    }        
}

}

I have a weird problem. If I run the program with the array set to 1 then you can log in, but if you run the code as I posted it and try to use the user and pass you set at index 2 it returns a invalid response, as listed below.

    run:
User id at index #0 tyler
Password at index #0 111
User id at index #1 jake
Password at index #1 111
User id at index #2 matt
Password at index #2 111
Enter user id: matt
Enter password: 111
Invalid user id/password combo!
BUILD SUCCESSFUL (total time: 15 seconds)

What am I doing wrong?

4
  • 2
    Binary search expects the array to be sorted. Unsorted arrays lead to unpredictable results Commented Apr 18, 2018 at 15:55
  • binarySearch will return the first index for the argument. You're searching for 111 which is at index 0, but matt for the username which is at index 2. 2 != 0. Commented Apr 18, 2018 at 15:56
  • @ErnestKiwele 's answer is also correct, but even if the array were sorted, it would still not work. Commented Apr 18, 2018 at 15:56
  • what would my go to be for this? Commented Apr 18, 2018 at 16:52

1 Answer 1

1

BinarySearch algorithm works only with sorted array:

Arrays.sort(userID);
Arrays.sort(password);
int x = Arrays.binarySearch(userID, userIdInput);
int y = Arrays.binarySearch(password, passwordInput);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.