繁体   English   中英

NumberFormatException 打印前必要的错误

[英]NumberFormatException printing before necessary error

当我运行我的代码的以下部分时,我得到以下结果它运行良好它只是在运行 do-while 循环之前打印 NumberFormatException 即使这不是我的代码中的一个选项,至少不是故意的。 请帮我理解这个错误谢谢!

控制台输出:输入要绘制的骰子数(重新滚动) - 最多 3:2 输入索引号(0 到 3),由您要绘制的骰子的空格分隔:java.lang.NumberFormatException:对于输入字符串:"" 再试一次 输入索引号(0 到 3),用空格隔开你想抽的骰子:0 1

掷骰子...

int[] tempIndex = new int[hands.getDrawNum()]; 布尔 tryAgain = true;

            do {
                try {
                    System.out.print("Enter the index numbers (0 to 3) separated by a space "
                            + "of the dice you wish to draw: ");
                    
                        String templine = input.nextLine();
                        String[] templineSplit = templine.split(" ");
                    
                    for (int i = 0; i < hands.getDrawNum(); i++) {
                        
                        tempIndex[i] = (Integer.parseInt(templineSplit[i]));
                    }
                    tryAgain = false;
                
                    for (int i = 0; i < hands.getDrawNum(); i++) {
                        if(!((tempIndex[i] >= 0) && (tempIndex[i] <= 3))) {
                        tryAgain = true;
                        throw new IllegalArgumentException();
                        }   
                }   
                }
                catch (InputMismatchException ime) {
                    System.out.println(ime);
                    System.out.println("Try again");
                    tryAgain = false;
                }
                catch (IllegalArgumentException iae) {
                    System.out.println(iae);
                    System.out.println("Try again");
                }
                catch (ArrayIndexOutOfBoundsException aiob) {
                    System.out.println(aiob);
                    System.out.println("Try again");
                    tryAgain = false;
                }
            } while(tryAgain);
            

尝试将格式不正确的字符串转换为数值时会发生NumberFormatException

在您的代码中唯一可能发生这种情况的地方是这里

tempIndex[i] = (Integer.parseInt(templineSplit[i]));

使用调试器或将tempIndex中的所有值打印到控制台以查看哪个不是有效数字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM