Java无止境输入对话框循环
我正在制作一个带有一些文本字段和提交按钮的GUI。 我正在尝试验证输入,以便在按下按钮时不会更改任何值,除非这些值验证了条件,但无论我给出了什么值,它都会保持循环 起初,我想用常规的消息对话框来执行,但我无法更改输入,因为窗口挡住了我的去路,如果我按OK,执行仍会继续,所以我就是这样进入输入对话框的。所以,是的,我真的非常感谢这里的帮助:)Java无止境输入对话框循环,java,Java,我正在制作一个带有一些文本字段和提交按钮的GUI。 我正在尝试验证输入,以便在按下按钮时不会更改任何值,除非这些值验证了条件,但无论我给出了什么值,它都会保持循环 起初,我想用常规的消息对话框来执行,但我无法更改输入,因为窗口挡住了我的去路,如果我按OK,执行仍会继续,所以我就是这样进入输入对话框的。所以,是的,我真的非常感谢这里的帮助:) intlandprice=((int)(Math.random()*(26-17))+17); int purchasedLand=0; 而(!inputA
intlandprice=((int)(Math.random()*(26-17))+17);
int purchasedLand=0;
而(!inputAccepted){
purchasedLand=Integer.parseInt(landBox.getText().trim());
如果((g.getGrain()-(purchasedLand*landPrice))<0)
purchasedLand=Integer.parseInt(JOptionPane.showInputDialog(landBox,
请重新输入购买土地的数量
+“我们负担不起给定的金额!”;
否则{
System.out.println(“耶”);
inputAccepted=true;
}
}
g.getGrain()
应该在开始时返回2800。您的问题来自这一行:
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;
}
}
intlandprice=((int)(Math.random()*(26-17))+17);
int purchasedLand=Integer.parseInt(landBox.getText().trim());
而(!inputAccepted){
如果((g.getGrain()-(purchasedLand*landPrice))<0)
purchasedLand=Integer.parseInt(JOptionPane.showInputDialog(landBox,
请重新输入购买土地的数量
+“我们负担不起给定的金额!”;
否则{
System.out.println(“耶”);
inputAccepted=true;
}
}
一旦你进入循环,用户就不可能更新字段的状态(它们被有效地锁定),好吧,那么我如何才能在不过度复杂化自己的情况下进行呢?很难知道,因为我不知道你是如何进入这个洞的。考虑提供一个说明你的问题的方法。这不是一个代码转储,而是您正在做的一个示例,它突出了您所遇到的问题。这将减少混乱,提高效率responses@MuadDib:下次你能正确缩进你的代码吗?
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;
}
}