mercredi 25 décembre 2019

While loop with JOptionPane returning StringIndexOutOfBounds Exceptions

In my code I have a while loop with 3 IF tests nested in between that have flags triggered by ELSE:

[test1] checks whether the input value has a length of exactly 1 [Prevents users from inputting nothing]

[test2] checks whether the input value at index 0 is a digit [I need a number as an input, but I'm using JSWING]

[test3] checks whether the input value length is greater than 1 [2 Digits (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;
                     }

The problem I'm having is somewhere between the first and second test. When I try inputting nothing as a value ["" / or just having an empty box and pressing enter], it detects the error of having nothing and displays "Input required" once, but once it loops, it outputs a StringIndexOutOfBoundsException for the second trial It works in every other case I've tried (no input -> correct, no-input -> incorrect...) Only sequential no-input cases crash the program.

The error is said to be in this line, but I don't understand where, or how.

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)

Aucun commentaire:

Enregistrer un commentaire