【问题标题】:Need Help Looping this when alphabet is input需要帮助 输入字母时循环播放
【发布时间】:2016-01-31 05:33:29
【问题描述】:
            do{
                try{
                    System.out.println("Enter the no of People");  
                    child = input.nextInt();
                    if(child < 0){
                        System.out.println("Enter a Positive Value");
                    }
                }
                    catch(InputMismatchException e){
                        input.next();
                        System.out.println("(Invalid Input! Enter a numeric Value"); <---- Will give out the error if user enters a character
                    }
            }while(child < 0);  

当用户输入字母时,程序在错误后结束 我需要在它之后循环它

【问题讨论】:

  • 对不起孩子 = input.nextInt();不是;对不起
  • 进入do while前child的值是多少?如果为0或者是实例变量,则循环不会继续循环...

标签: java validation loops


【解决方案1】:

由于您没有对我的问题发布任何答案,这里是一个猜测答案,但我很确定问题如下:

child 变量在进入循环时肯定有 0 或更大的值。当尝试将String 转换为int 时,child 的值当然不会改变,因此测试未完成。

这是一个在catch 子句中使用的简单技巧:

catch(InputMismatchException e){
    input.next();
    System.out.println("(Invalid Input! Enter a numeric Value");
    child = -1;
}

只需将child 设置为小于0,这样当您捕获异常时,它总是会循环回来。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    相关资源
    最近更新 更多