我正在尝试确定当前数组中是否已经存在用户输入的值,该怎么做?
用户输入的值来检查变量是 accno并且要比较的数组是 accnums
这就是我目前正在做的事情
public class Randomtopic {
static BigDecimal[] accbal = new BigDecimal[20];
static Integer[] accnums = new Integer[20];
public static void main(String[] args) {
displayMenu();
}
public static void displayMenu() {
int option, accno;
double accbal;
Scanner sc = new Scanner(System.in);
System.out.println(" Add an account");
System.out.println("Search an account with the given account number");
System.out.print("Enter Your Choice: ");
option = sc.nextInt();
switch (option) {
case 1:
System.out.println("You have choosen to add account");
addAccount();
break;
case 2:
System.out.println("You have choosen to search for an account");
System.out.print("Enter the Account Number: ");
accno = sc.nextInt();
System.out.println(search(accno, accnums));
break;
default:
System.out.println("Please choose an appropriate option as displayed");
}
displayMenu();
}
public static void addAccount() {
//String accno;
int i = 0;
int accno, input;
BigDecimal accbala;
DecimalFormat df = new DecimalFormat("0.00");
//BigDecimal[] accbal= new BigDecimal[20];
Scanner sc = new Scanner(System.in);
//String[] accnums = new String[20];
int j;
System.out.print("Enter the account number: ");
accno = sc.nextInt();
if (String.valueOf(accno).matches("[0-9]{7}")) {
System.out.print("Enter account balance: ");
accbala = sc.nextBigDecimal();
for (j = 0; j < accnums.length; j++) {
if (accnums[j] == null )
break;
else if(accnums[j].equals(accno))
{
System.out.println("Account already exists");
}
}
//System.out.print(j);
if (j == accnums.length) {
System.out.print("Account storage limit has reached.");
} else {
accnums[j] = accno;
accbala = accbala.setScale(2, RoundingMode.HALF_UP);
accbal[j] = accbala;
}
input = accnums[0];
System.out.println("The value: " + input + " witha a balance of " + accbal[0].toString());
} else {
System.out.println("Wrong NRIC");
}
displayMenu();
}
public static String search(int accnum, Integer[] numbers) {
// Integer[] numbers;
//int key;
//numbers = accnums;
// System.out.print("Enter the Account Number: ");
for (int index = 0; index < numbers.length; index++) {
if (numbers[index].equals(accnum)) {
return String.valueOf(index);
// System.out.println("The account number exists in this array index :"+index);//We found it!!!
}
break;
}
return "-1";
}
}
所以我的问题?当我第一次输入 accnum 时,我得到 NullPointerException。Tks