gpt4 book ai didi

java - Try and Catch with JOption 未按预期工作

转载 作者:行者123 更新时间:2023-12-01 12:37:45 25 4
gpt4 key购买 nike

    int i=0;
int c=0;
int a=0;
int b=0;
String stringy;
String input;

do { //loop for value a
try // try-catch to prevent program from crashing
{
stringy= JOptionPane.showInputDialog("Type a value for a or press q to quit:");
if (stringy.equalsIgnoreCase("q")) System.exit(0);
a = Integer.parseInt(stringy);
i++;
} catch (Exception e) {
stringy= JOptionPane.showInputDialog("Error. Try Again! ");
} // end catch
} while(i==0); // end loop

输出产生一个jOption输入对话框(“键入一个值...”),当我输入一个字符串或系统不期望的内容时,它会转到“catch”并弹出“错误重试!”但是,当我输入任何内容时,即使它是一个数字,它也会返回到(“输入一个值...”)对话框。我希望它读取错误框中的输入,而不是跳回第一个对话框。感谢您的帮助!

最佳答案

如果您想使用来自 catch() 的输入,您应该将基本输入从循环中取出。并使用 break; 子句代替 while(i==0)i++;

       stringy= JOptionPane.showInputDialog("Type a value for a or press q to quit: ");
while(true)
{
if (stringy.equalsIgnoreCase("q")) System.exit(0);
try {
a = Integer.parseInt(stringy);
break;
} catch (Exception e) {
stringy= JOptionPane.showInputDialog("Error. Try Again! ");
}
}
JoptionPane.showMessageDialog("Input accepted!");

请以正确的格式编写您的代码,您已在循环开始时注释了“{”。

关于java - Try and Catch with JOption 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25421974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com