gpt4 book ai didi

java - JOptionPane 的 While 循环返回 StringIndexOutOfBounds 异常

转载 作者:行者123 更新时间:2023-12-01 19:11:16 24 4
gpt4 key购买 nike

在我的代码中,我有一个 while 循环,其中嵌套了 3 个 IF 测试,这些测试具有由 ELSE 触发的标志:

[test1]检查输入值的长度是否正好为1[防止用户不输入任何内容]

[test2] 检查索引 0 处的输入值是否为数字 [我需要一个数字作为输入,但我正在使用 JSWING]

[test3]检查输入值长度是否大于1[2位(10,11,12,...)

 num1= JOptionPane.showInputDialog(null,"Please input Guess #" + (counter+1), "0"); 
while(exit == false || test1 == false || test2 == false || test3 == false) {
if(num1.length() < 1) {
JOptionPane.showMessageDialog(null,"Input required");
num1= JOptionPane.showInputDialog(null,"Please input Guess #" + (counter+1), "0");
}
else {
test1 = true;
}
if(Character.isDigit(num1.charAt(0)) == false) {
JOptionPane.showMessageDialog(null,"Input has to be a number between 0 - 9.");
num1= JOptionPane.showInputDialog(null,"Please input Guess #" + (counter+1), "0");
}
else {
test2 = true;
}
if(num1.length() > 1) {
JOptionPane.showMessageDialog(null,"Input has to be a number between 0 - 9.");
num1= JOptionPane.showInputDialog(null,"Please input Guess #" + (counter+1), "0");
}
else {
test3 = true;
}
if(test1 == true && test2 == true && test3 == true) {
exit = true;
}

我遇到的问题介于第一次测试和第二次测试之间。当我尝试不输入任何内容作为值 [""/或者只是有一个空框并按 Enter] 时,它会检测到没有任何内容的错误并显示一次“需要输入”,但一旦循环,它会在第二次输出 StringIndexOutOfBoundsException审判它适用于我尝试过的所有其他情况(无输入 -> 正确,无输入 -> 不正确...)只有连续的无输入情况才会导致程序崩溃。

据说错误就在这一行,但我不明白在哪里,或者如何。

if(Character.isDigit(num1.charAt(0)) == false)

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:709)
at oof.Lottery_Swing_FIX.main(Lottery_Swing_FIX.java:56)

固定逻辑

                JOptionPane.showMessageDialog(null,"Enter 3 one-digit positive numbers for your 3 guesses");
for(int counter = 0; counter < LIMIT; counter++) {
test = false;

while(exit == false || test == false) {
num1= JOptionPane.showInputDialog(null,"Please input Guess #" + (counter+1), "");
if(num1.length() < 1 || Character.isDigit(num1.charAt(0)) == false || num1.length() > 1) {
JOptionPane.showMessageDialog(null,"Integer between 1-9 required");
}
else {
test = true;
}
if(test == true) {
numberInput = Integer.parseInt(num1);
exit = true;
}
else {
continue;
}
}

最佳答案

您的“修复”不处理null,如果对话框关闭(xJOptionPane.showInputDialog()将返回该值>) 或取消 Cancel 按钮被选中。您不能像使用 Null String 那样对 String#length() 方法使用 null em> ("") 因此,您需要在代码中检查这一点,否则最终可能会出现 NullPointerException。您可以在第一个 if 语句中将其作为条件组件执行此操作:

if (num1 == null) {
// The CANCEL or dialog close button was selected.
}

您的代码中确实不需要这些 boolean 标志。事情要么会发生,要么根本不会发生。你真的不需要旗帜来提醒你离家这么近(可以这么说)。如果您在 if 语句中正确建立了条件并使用 else if,则不需要它们。话虽如此,您也不需要在 while 循环的条件内使用这些 boolean 标志。

while 循环需要关注一件事......提示提供了有效的数据。如果不是,则保存提示数据的变量 (num1) 将转换为空字符串 ("")。所以实际上:

String num1 = "";
while (num1.equals("")) { .... }

因此,只要 num1 包含空字符串 (""),我们就继续循环,从而重新提示正确的输入。

在您的代码中,您希望向用户提供有关输入失败原因的具体详细信息。有多种方法可以执行此操作,但是无论您选择哪种方式,请确保它不会生成任何可能最终停止您的应用程序或改变其准确性能的异常(错误)。在当前用例中使用 ifelse if 语句来执行此特定任务没有任何问题。遵循您的特定主题:

int LIMIT = 3, numberInput;
int[] guesses = new int[LIMIT];
String errMsg;
String num1;
JOptionPane.showMessageDialog(null, "<html>You will be prompted three times "
+ "to supply<br>a positive <font color=red><b>single digit</b></font> "
+ "number.</html>", "Information", JOptionPane.INFORMATION_MESSAGE);
for (int counter = 0; counter < LIMIT; counter++) {
num1 = "";
while (num1.equals("")) {
errMsg = "";
num1 = JOptionPane.showInputDialog(null, "Please input Guess #" + (counter + 1),
"Guess #" + (counter + 1),JOptionPane.QUESTION_MESSAGE);
// Does num1 contain null?
if (num1 == null) {
if (JOptionPane.showConfirmDialog(null,
"<html>You <font color=blue>canceled</font> your input!<br>"
+ "Do you want to quit?</html>", "Quit",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
System.exit(0);
}
num1 = ""; // Set for re-prompt.
continue;
}
// Is nothing supplied?
else if (num1.length() < 1) {
errMsg = "<html><font size=5 color=red><center>Nothing Supplied!"
+ "</center></font><br>You must provide a single Integer "
+ "value between<br>0 and 9 (inclusive).</html>";
}
// Is too much supplied?
else if (num1.length() > 1) {
errMsg = "<html><center><font size=5 color=red>To Much Supplied!</font><br>" +
"<font size=5 color=blue>\"" + num1 + "\"</font></center><br>" +
"You must provide a single Integer value between<br>0 and 9 "
+ "(inclusive).</html>";

}
// Is the supplied character a number?
else if (!Character.isDigit(num1.charAt(0))) {
errMsg = "<html><center><font size=5 color=red>Invalid Digit Supplied!"
+ "</font><br><font size=5 color=blue>\"" + num1 + "\"</font>"
+ "</center><br>You must provide a single Integer value "
+ "between<br>0 and 9 (inclusive).</html>";
}

// Does errMsg actually contain a message? If so display it.
if (!errMsg.equals("")) {
JOptionPane.showMessageDialog(null, errMsg, "Invalid Input!",
JOptionPane.WARNING_MESSAGE);
num1 = ""; // Set for re-prompt.
}
else {
numberInput = Integer.parseInt(num1);

// ... do whatever you want to do with numberInput, for example ....
guesses[counter] = numberInput;
}
}
}

// Display User's LIMITED guesses:
StringBuilder sb = new StringBuilder();
sb.append("<html>The <font color=red><b>").append(LIMIT).
append("</b></font> Guesses supplied by User are:<br><br>");

for (int i = 0; i < guesses.length; i++) {
sb.append("Guess #").append((i + 1)).append(": <font color=blue>").append(guesses[i]).append("</font><br>");
}
sb.append("</html>");

JOptionPane.showMessageDialog(null, sb.toString(), "Guesses Provided",
JOptionPane.INFORMATION_MESSAGE);

如您所见,向用户提供有关输入失败的详细信息需要更多代码。如果您决定只想要一个简单的“无效输入!”,则可以删除所有这些代码。信息。这本质上迫使用户更加认真地阅读所提供的提示,例如:

int LIMIT = 3;
int numberInput;
int[] guesses = new int[LIMIT];
String num1;
JOptionPane.showMessageDialog(null, "<html>You will be prompted three times "
+ "to supply<br>a positive <font color=red><b>single digit</b></font> "
+ "number.</html>", "Information", JOptionPane.INFORMATION_MESSAGE);
for (int counter = 0; counter < LIMIT; counter++) {
num1 = "";
while (num1.equals("")) {
num1 = JOptionPane.showInputDialog(null, "Please input Guess #" + (counter + 1),
"Guess #" + (counter + 1),JOptionPane.QUESTION_MESSAGE);
// Does num1 contain null?
if (num1 == null){
if (JOptionPane.showConfirmDialog(null,
"<html>You <font color=blue>canceled</font> your input!<br>"
+ "Do you want to quit?</html>", "Quit",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
System.exit(0);
}
num1 = ""; // Set for re-prompt.
}
else if (!num1.matches("\\d")) {
JOptionPane.showMessageDialog(null, "<html><center><font size=5 color=red>Invalid Input Supplied!</font><br>" +
"<font size=5 color=blue>\"" + num1 + "\"</font></center><br>" +
"You must provide a single Integer value between<br>0 and 9 "
+ "(inclusive).</html>", "Invalid Input!", JOptionPane.WARNING_MESSAGE);
num1 = "";
}
else {
numberInput = Integer.parseInt(num1);

// ... do whatever you want to do with numberInput, for example ....
guesses[counter] = numberInput;
}
}
}

// Display User's LIMITED guesses:
StringBuilder sb = new StringBuilder();
sb.append("<html>The <font color=red><b>").append(LIMIT).
append("</b></font> Guesses supplied by User are:<br><br>");

for (int i = 0; i < guesses.length; i++) {
sb.append("Guess #").append((i + 1)).append(": <font color=blue>").append(guesses[i]).append("</font><br>");
}
sb.append("</html>");
JOptionPane.showMessageDialog(null, sb.toString(), "Guesses Provided",
JOptionPane.INFORMATION_MESSAGE);

特别注意上面代码中else if语句的条件(!num1.matches("\\d))。这里使用了String#matches() 方法与一个小的 Regular Expression ("\\d" 表达式)一起使用。该表达式告诉 ma​​tches() 方法查看我们的字符串是否为re 匹配(在 num1 中)是一个单个数字字符串数值(例如:“5”)。那么,else if声明询问:

else if num1 中包含的字符串NOT (!) 是一个数字字符串数值,然后运行大括号中的代码({...})。这基本上涵盖了除 null 之外的所有输入失败(因为我们将其作为退出选项处理)和 String#matches()方法不会接受 null。

如果您不需要退出选项,那么您只需要在代码中添加一个if语句即可:

if (num1 == null || !num1.matches("\\d")) { ... }

关于java - JOptionPane 的 While 循环返回 StringIndexOutOfBounds 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59480258/

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