我正在尝试在数组中搜索一个值,并决定使用内置的二进制搜索来执行此操作。我有一堂课:
import java.util.*;
public class Charge {
private int isAcct;
private int[] acctNumbers = {5658845,4520125,7895122,8777541,8451277,
1302850,8080152,4562555,5552012,5050552,7824577,
1250255,1005231,6545231,3852085,7576651,7881200,
4851002};
public Charge(int aNum) {
isAcct = aNum;
}
public Boolean isValidAcctNumber() {
int m = Arrays.binarySearch(acctNumbers, isAcct);
if (m == -1)
return false;
else
return true;
}
}
和一个测试:
import java.util.Scanner;
public class ChargeTest {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("What is your account number?: ");
int num = scan.nextInt();
Charge charge = new Charge(num);
System.out.println(charge.isValidAcctNumber());
if (charge.isValidAcctNumber() == false) {
System.out.println("Your account "+num+" is not a valid account");
} else {
System.out.println("Your account "+num+" is a valid account");
}
}
}
这适用于某些数字,例如 4851002,但不适用于其他数字,例如 1302850。我真的不知道为什么。我很可能只是手动实现二进制搜索,但我对为什么这不起作用感到困惑。