我正在尝试编写验证提款金额的代码。例如,如果提款金额大于余额,则应出现错误并说“无效提款金额”,但问题是当我输入无效金额时,会弹出错误消息。我尝试输入有效金额,它不会接受任何东西!它甚至不会让我关闭对话框。我该如何解决这个问题?
if (transactionChar== 'W' || transactionChar == 'w')
{
input = JOptionPane.showInputDialog("Please enter withdrawal amount.");
transactionAmount = Double.parseDouble(input);
while(transactionAmount >= oldBalance)
input = JOptionPane.showInputDialog("Invalid withdrawal amount. Please enter valid withdrawal amount!");
transactionAmount = Double.parseDouble(input);
newBalance = oldBalance - transactionAmount;
}
我的声明是
double oldBalance= 0; //Holds the value of the old balance
String transactionType= ""; //Holds the value of the transaction type.
char transactionChar ; //Gets input for either withdrawal or deposit
double transactionAmount= 0;
答案 0 :(得分:2)
while(transactionAmount >= oldBalance)
input = JOptionPane.showInputDialog("Invalid withdrawal amount. Please enter valid withdrawal amount!");
您永远不会根据输入更新transactionAmount,因此while循环永远不会停止
试试这个
while(transactionAmount >= oldBalance) {
input = JOptionPane.showInputDialog("Invalid withdrawal amount. Please enter valid withdrawal amount!");
transactionAmount = Double.parseDouble(input);
}
您应该注意的其他几件事情:
如果我的帐户中有$ 100.00(oldBalance = 100.0)并且我尝试从我的帐户中提取100.00(transactionAmount == oldBalance),那么您的代码不允许我这样做。你不要让我把我的账户归零!
此外,似乎你要让我撤回负数。那是我的退步!! :d
答案 1 :(得分:0)
尝试使用
while(condition)
{
statement1;
statement2;
}
而不是
while(condition)
statement1;
statement2;
答案 2 :(得分:0)
如果您没有正确格式化代码,很难回答,但我认为您的代码是这样的:
if (transactionChar== 'W' || transactionChar == 'w') {
input = JOptionPane.showInputDialog("Please enter withdrawal amount.");
transactionAmount = Double.parseDouble(input);
while(transactionAmount >= oldBalance)
input = JOptionPane.showInputDialog("Invalid withdrawal amount. Please enter valid withdrawal amount!");
transactionAmount = Double.parseDouble(input);
newBalance = oldBalance - transactionAmount;
}
问题是您需要一个块{}来包含交易金额分配:
if (transactionChar== 'W' || transactionChar == 'w') {
input = JOptionPane.showInputDialog("Please enter withdrawal amount.");
transactionAmount = Double.parseDouble(input);
while(transactionAmount >= oldBalance) {
input = JOptionPane.showInputDialog("Invalid withdrawal amount. Please enter valid withdrawal amount!");
transactionAmount = Double.parseDouble(input);
}
newBalance = oldBalance - transactionAmount;
}