【发布时间】:2019-07-29 12:48:26
【问题描述】:
您好,我有一个包含银行数据的数组类: 帐号、余额、账户类型和状态。 数组是用构造函数构建的:
Bank.accounts.add(new Account(this.accNumber, this.type, this.balance, this.status));
当我尝试找到一个数字(使用不同的方法)时,它没有找到。
该方法获取银行号码帐户的输入,然后将其与帐户数组列表进行比较。如果找到,则会打开一个控制台界面,但它永远不会找到帐号。 我尝试过扫描整数、字符串到整数,并在方法内部使用 contains 方法或作为独立方法(如下面的示例)使用,但没有成功。
方法是:
public void accountActions() {
System.out.println("Enter number of account for more info");
Boolean isFinished = false;
while (!isFinished) {
try {
String scan = input.nextLine();
Bank.number = Integer.parseInt(scan);
isFinished = true;
} catch (NumberFormatException e) {
System.out.println("Please enter again\n------------------------------");
isFinished = false;
} catch (InputMismatchException e) {
System.out.println("Please enter again\n------------------------------");
isFinished = false;
}
}
if (checkAccountNumber(number) == true) {
System.out.println("=====================================");
System.out.println("= =");
System.out.println("= Enter command number =");
System.out.println("= =");
System.out.println("= 1. Withdraw money =");
System.out.println("= 2. Deposit =");
System.out.println("= 3. Total money in all accounts =");
System.out.println("= =");
System.out.println("=====================================");
} else {
System.out.println(
"No account was found by that number, would you like to try again?\n(((Yes/No)))\n---------------");
yesNo("accountActions");
}
}
而独立的方法是:
public boolean checkAccountNumber(int a) {
boolean check = false;
if (Bank.accounts.contains(a)) {
check = true;
}
return check;
}
【问题讨论】:
-
你应该避免在你的集合中使用原始类型。
-
请注意,将
Bank.accounts数据结构建模为从帐号到Account的哈希表可能是更好的设计。然后您可以简单地查找一个帐号。
标签: java arraylist collections contains