I am trying to search an array for a value and decided to use the built in binary search to do so. I have a class:
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;
}
}
And a test:
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");
}
}
}
This works for certain numbers like 4851002, but not others like 1302850. I really haven't the foggiest idea why. I will most likely just implement binary search by hand, but I am confused as to why this doesn't work.