我试图在switch语句中创建验证,只允许正整数但是当我尝试输入一个负整数时,它会输出错误信息,但不会重复循环而只是继续。
这就是我想出的。有人可以告诉我哪里出错了吗?
public void InsertMoney()
{
String soption;
productName = " Nothing";
// Vending machine welcome dialog
soption = JOptionPane.showInputDialog(
"============================================"
+ "\nWelcome to the College Vending Machine!"
+ "\n============================================"
+ "\n\nOptions: i for insert money, s for select item, q for quit."
+ "\n\n============================================");
switch (soption)
{
case "q": // user chooses q to quit
JOptionPane.showMessageDialog(null, "Have a Nice Day!");
System.exit(0); // terminate application
break;
case "i": // if user chooses i: insert money;
do
{
spaymentSum = JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n============================="); // Inserting money
paymentSum = Integer.parseInt(spaymentSum); // Parsing for calculations
if (paymentSum <= 0)
{
JOptionPane.showMessageDialog(null,"Must be a positive input! Try again.");
}
} while (paymentSum > 0);
break;
case "s": // if user chooses s: select item
break;
}
}
答案 0 :(得分:0)
根据AntonH的建议,我添加了while (paymentSum <=0)
而不是我最初在while (paymentSum > 0)
写的内容,并且它有效。
谢谢AntonH!
新的工作代码是:
public void InsertMoney()
{
String soption;
productName = " Nothing";
// Vending machine welcome dialog
soption = JOptionPane.showInputDialog(
"============================================"
+ "\nWelcome to the College Vending Machine!"
+ "\n============================================"
+ "\n\nOptions: i for insert money, s for select item, q for quit."
+ "\n\n============================================");
switch (soption)
{
case "q": // user chooses q to quit
JOptionPane.showMessageDialog(null, "Have a Nice Day!");
System.exit(0); // terminate application
break;
case "i": // if user chooses i: insert money;
do
{
spaymentSum = JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n============================="); // Inserting money
paymentSum = Integer.parseInt(spaymentSum); // Parsing for calculations
if (paymentSum <= 0)
{
JOptionPane.showMessageDialog(null,"Must be a positive input! Try again.");
}
} while (paymentSum <= 0); // ADDED CHANGES HERE
break;
case "s": // if user chooses s: select item
break;
}
}