我创建了一个关于 ATM 机的应用程序,其数组帐户大小为 10,但由于某种奇怪的原因,输入只接受 0(第一个 id(,但不接受其他 9 个 id,它总是显示无效的 id 错误消息。我已经坚持了几个小时寻找错误。
与检查 ID 相关的是这两个;
public static boolean hasID(Account acc[], int id){ //this is to check whether the id exist or not.
for(int i=0; i<acc.length; i++){
if(id == acc[i].getID()){
return true;
}
}
return false;
}
public static int gID(Account[] acc){ //this is the login method to initiate the hasID method.
Scanner sc = new Scanner(System.in);
int id=0;
boolean valid = false;
while(!valid){
System.out.println("Enter ID: ");
id = sc.nextInt();
if(!hasID(acc, id)){
System.out.println("YOUR ID IS INVALID.");
} else{
valid = true;
}
}
return id;
}
public Account(int mID, double mBalance/*, double mInterestRate*/){
this.id = getID();
this.balance = getBalance();
//this.interestRate = getInterestRate();
}
public static Account getAccount(Account acc[], int id){
for(int i = 0; i<acc.length; i++){
if(id == acc[i].getID()){
return acc[i];
}
}
return null;
}
这是我的主要:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Account acc[] = new Account[10];
for(int i = 0; i<acc.length; i++){
acc[i] = new Account(i, 100.0);
}
int a = 0;
int id = gID(acc);
while(a != 4){
Account ac = getAccount(acc,id);
System.out.println("1: Check Balance");
System.out.println("2: Withdraw");
System.out.println("3: Deposit");
System.out.println("4: Exit");
System.out.println("Enter your choice: ");
a = sc.nextInt();
switch(a){
case 1:
System.out.println("Your Balance is: RM " + ac.getBalance());
break;
case 2:
System.out.println("Amount to withdraw: RM ");
ac.withdraw(sc.nextDouble());
break;
case 3:
System.out.println("Amount to deposit: RM ");
ac.deposit(sc.nextDouble());
break;
case 4:
id = gID(acc);
a = 0;
break;
default:
System.out.println("Invalid input!");
}
}
}
编辑:帐户构造函数,不使用 insterestrate。id和余额的二传手和吸气器:
public int getID(){
return id;
}
public void setID(int mID){
id = mID;
}
public double getBalance(){
return balance;
}
public void setBalance(double mBalance){
balance = mBalance;
}
谢谢你的时间。
public Account(int mID, double mBalance/*, double mInterestRate*/){
this.id = getID();
this.balance = getBalance();
//this.interestRate = getInterestRate();
}
你不应该使用
public Account(int mID, double mBalance/*, double mInterestRate*/){
this.id = mID;
this.balance = mBalance;
//this.interestRate = getInterestRate();
}
getter 和 setter 是 FIELDS 封装的一部分,但为了更好的用户体验,我可以建议你使用以下代码
public Account(/*you dont need a parameter*/){
this.id = setIdByScannedValue();
this.balance = setBalanceByScannedValue();
//this.interestRate = setInterestRateByScannedValue();
}
private void setIdByScannedValue(){
Scanner sc = new Scanner(System.in);
boolean provided = false;
while(!provided)
try{
System.out.print("provide id: ");
this.id = sc.nextInt();
}catch(NumberFormatException e){
System.out.println("you must provide an integer id format !!!");
}finally{
provided = true;
}
}
我会让你做其他方法,这样你就可以自己学习使用这个想法,这样我就能确保你理解我的代码。