我正在尝试执行类似ATM的程序,但如果用户存入的值小于100,我需要警告用户。我只需要设置一个条件,输出"无效金额,输入值小于100">
public static void TransactDeposit(int iNum, int iName, int iBal, int iCol, int accType)
{
Heading();
String newBalance = "", depositAmt = "";
double convAmt = 0.00, accBalance = 0.00;
System.out.println("tt Enter X to Exit");
System.out.println("nt Enter Amount to be Deposited: ");
System.out.print("ttt ");
depositAmt = scan.next();
if (depositAmt.matches("\d+"))
{
if (accType % 100 == 0)
{
convAmt = Double.parseDouble(depositAmt);
accBalance = Double.parseDouble(accountInfo[2][iCol]);
accBalance = accBalance + convAmt;
newBalance = String.valueOf(formatter.format(accBalance));
accountInfo[2][iCol] = newBalance;
}
else if (accType == 1)
{
convAmt = Double.parseDouble(depositAmt);
accBalance = Double.parseDouble(newAccount[2][iCol]);
accBalance = accBalance + convAmt;
newBalance = String.valueOf(formatter.format(accBalance));
newAccount[2][iCol] = newBalance;
}
System.out.println("ntt Deposited: " + depositAmt);
System.out.println("nt----------------------------------------");
System.out.println("nt Press Enter to Go Back...");
scan.nextLine();
if (scan.nextLine() != null)
{
ClearScreen();
AtmMenu(iNum, iName, iBal, iCol, accType);
}
}
else if (depositAmt.equalsIgnoreCase("x"))
{
ClearScreen();
AtmMenu(iNum, iName, iBal, iCol, accType);
}
else
{
System.out.println("nt----------------------------------------");
System.out.println("ntInvalid Key! Press Enter to Try Again...");
scan.nextLine();
if (scan.nextLine() != null)
{
ClearScreen();
TransactDeposit(iNum, iName, iBal, iCol, accType);
}
}
}
将值转换为double
后,检查其是否小于100
。如果是,打印错误消息并中止或递归调用。否则,继续更新帐户。
注意,我已经删除了regex,并用try/catch替换。
// ....
// Check special case first
if (depositAmt.equalsIgnoreCase("x")) {
ClearScreen();
AtmMenu(iNum, iName, iBal, iCol, accType);
}
else {
try {
double convAmt = Double.parseDouble(depositAmt);
if (convAmt < 100) {
System.out.println("Invalid amount, inputted value is less than 100");
ClearScreen();
TransactDeposit(iNum, iName, iBal, iCol, accType);
return;
}
// User input OK. Can continue...
// Code to update account removed for brevity....
}
catch (NumberFormatException ex)
System.out.println("nt----------------------------------------");
System.out.println("ntInvalid Key! Press Enter to Try Again...");
scan.nextLine();
ClearScreen();
TransactDeposit(iNum, iName, iBal, iCol, accType);
}
}
}