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?
binarySearchwill return the first index for the argument. You're searching for111which is at index 0, butmattfor the username which is at index 2.2 != 0.