我目前正在尝试编写一个方法,该方法首先会请求存款、取款或退出。
然后询问帐户名称(这会按名称从数组列表中获取帐户)
然后提示输入所选存款或取款的金额。
然后返回到(存款、取款、退出)提示
我写的代码顺序错误。 (它要求输入名称,然后是操作,然后是金额),我不知道如何将其更改为上面所需的顺序。
我也无法弄清楚如何让循环在输入为 3 时退出。
我想我已经很接近了...只是似乎无法从这里继续前进。 (ps while true 循环只是我在尝试找出其余部分时使用的临时循环)
public void banking()
{
while(true)
{
Scanner scan4 = new Scanner(System.in);
System.out.println("please enter the name for the account"); //takes the name of the account to select the correct object in arraylist
String accountName = scan4.nextLine();
for(Account y: accounts) //for all the objects in the arraylist...
{
while(accountName.equalsIgnoreCase(y.getName()))
{
Scanner scan3 = new Scanner(System.in);
System.out.println("1:Deposit 2:Withdraw 3:Quit");
int request = scan3.nextInt();
if(request == 1)
{
Scanner scan = new Scanner(System.in);
System.out.println("please make a deposit");
double newBalance = scan.nextDouble();
y.deposit(newBalance);
}
else if (request == 2)
{
Scanner scan2 = new Scanner(System.in);
System.out.println("please make a withdrawl");
double withdrawl = scan2.nextDouble();
if(withdrawl > y.getBalance())
{
System.out.println("Insufficient funds");
}
else
{
y.withdraw(withdrawl);
}
}
else if (request == 3)
{
break;
}
}
}
}
}
最佳答案
我想您只是想将顺序更改为以下内容:
- 操作(存款、取款、退出)
- 帐户名称
- 金额(仅限存款/取款)
这可以通过扫描方法开头的操作轻松实现。 所以你只需要把这部分移到你的 wile-loop 的开头:
Scanner scan3 = new Scanner(System.in);
System.out.println("1:Deposit 2:Withdraw 3:Quit");
int request = scan3.nextInt();
此外,您还必须将第二个 while 循环更改为 if 语句。否则,一旦输入,循环就不会停止,并且无法选择不同的操作。
所以改变这个:
while(accountName.equalsIgnoreCase(y.getName()))
对此:
if(accountName.equalsIgnoreCase(y.getName()))
因此更正后的代码将如下所示:
public void banking()
{
while(true)
{
Scanner scan3 = new Scanner(System.in);
System.out.println("1:Deposit 2:Withdraw 3:Quit");
int request = scan3.nextInt();
Scanner scan4 = new Scanner(System.in);
System.out.println("please enter the name for the account"); //takes the name of the account to select the correct object in arraylist
String accountName = scan4.nextLine();
for(Account y: accounts) //for all the objects in the arraylist...
{
if(accountName.equalsIgnoreCase(y.getName()))
{
if(request == 1)
{
Scanner scan = new Scanner(System.in);
System.out.println("please make a deposit");
double newBalance = scan.nextDouble();
y.deposit(newBalance);
}
else if (request == 2)
{
Scanner scan2 = new Scanner(System.in);
System.out.println("please make a withdrawl");
double withdrawl = scan2.nextDouble();
if(withdrawl > y.getBalance())
{
System.out.println("Insufficient funds");
}
else
{
y.withdraw(withdrawl);
}
}
else if (request == 3)
{
break;
}
}
}
}
}
效率还可以进一步提高。例如,如果用户选择“退出”,则避免 for 循环。 (但这是可选的,不是必需的)
尽管这可以解决您的问题,但我必须告诉您,您永远不应该使用 true
作为 while 循环的条件。
关于java - 如何重构银行方法中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52257066/