Java无尽输入对话循环

时间:2016-01-04 22:48:07

标签: java

我正在制作带有一些文本字段和提交按钮的GUI。     我正在尝试验证输入,以便在按下按钮时不会更改任何值,除非值验证条件,但无论我给出的值如何,它都会保持循环。

起初我想用常规的消息对话框来做,但是我无法改变输入,因为窗口挡住了,如果我按下OK,无论如何都会继续执行,这就是我输入对话框的方式。所以,是的,我真的很感激一些帮助:)

int landPrice = ((int) (Math.random() * (26 - 17)) + 17);
int purchasedLand=0;

while (!inputAccepted) {
    purchasedLand = Integer.parseInt(landBox.getText().trim());
    if ((g.getGrain() - (purchasedLand * landPrice)) < 0)
        purchasedLand = Integer.parseInt(JOptionPane.showInputDialog(landBox, 
                    "please re-input the amount of purchased land,"
                  + " we cannot afford the given amount! "));
    else {
        System.out.println("yay");
        inputAccepted = true;
    }
}

g.getGrain()应该在开始时返回2800。

1 个答案:

答案 0 :(得分:2)

你的问题来自这一行:

purchasedLand = Integer.parseInt(landBox.getText().trim());

虽然您更新了JOptionPane中的变量,但始终将其设置回landBox.getText().trim(),因此您永远不会到达else声明。

最终解决方案

int landPrice = ((int) (Math.random() * (26 - 17)) + 17);
int purchasedLand =Integer.parseInt(landBox.getText().trim());

while (!inputAccepted) {

    if ((g.getGrain() - (purchasedLand * landPrice)) < 0)
        purchasedLand = Integer.parseInt(JOptionPane.showInputDialog(landBox, 
                    "please re-input the amount of purchased land,"
                  + " we cannot afford the given amount! "));
    else {
        System.out.println("yay");
        inputAccepted = true;
    }
}