数组未使用Arrays.binarySearch返回正确的响应

时间:2018-04-18 15:51:20

标签: java arrays

好的,这是我的代码。

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

}

我有一个奇怪的问题。如果我运行程序并将数组设置为1,那么您可以登录,但是如果您在我发布它时运行代码并尝试使用该用户并通过您在索引2处设置它将返回无效响应,如下所示。

    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)

我做错了什么?

1 个答案:

答案 0 :(得分:1)

BinarySearch 算法 排序数组

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