同时尝试捕获JAVA验证 [英] Do while with try catch JAVA validation

查看:65
本文介绍了同时尝试捕获JAVA验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我输入字母和其他类型时,当我调用此方法时它停止时,我很难弄清楚如何解决这个问题。我的代码有什么问题?我正在使用netbeans。有人可以帮忙吗?提前致谢!



这是我的代码:



I'm having a trouble figuring out how to solve this issue when it just stops when I call this method when I input letters and other types. What is the problem with my code? Im using netbeans. Can anyone help? Thanks in advance!

Here is my code:

public int selectOption(int maxRange, String sourceType) throws IOException
{
    do
    {
        try
        {
            userInput = input.nextInt();

        }//end try
        catch(Exception e)
        {
            validInput=false;
            input.next();

        }//end catch

        if (userInput<1 || userInput>maxRange)
        {
            MovieHouse.clearScreen();
            System.out.println("Select from the options only!");
            loadHeader();

            if(sourceType.equals("main"))
                MovieHouse.homeMenu();
            else if(sourceType.equals("movie menu"))
                loadMovieMenu();

        }//end if

    }while(userInput<1 || userInput>maxRange || validInput==false);

    return userInput;

}//end selectOption

推荐答案

- 为什么还有一个抛出声明,当还有一个try / catch insde来阻止它?

- 为什么 boolean validInput只触及所说的捕获?什么时候会是真的?

- 为什么你在userInput< 1 || userInput> maxRange条件下做出反应?剩下的会怎么样?

- 为什么循环运行只要这个条件为真(我假设,因为validInput永远不会是真的)?



我建议重新开始。



我也宣布这是一项基本的家庭作业 - 请具体询问。
- why is there "throws" declaration when there's also a try/catch insde to prevent that?
- Why is the boolean "validInput" only touched in said catch? When will it be true?
- why are you reacting in if condition on "userInput<1 || userInput>maxRange" ? What happens to the rest?
- Why is the loop running as long as this condition is true (I'm assuming, cause "validInput" will never be true)?

I suggest to start over.

Also I declare this to be a basic homework task - please ask specific.


看看我最近的文章,希望它可以给你一些方向:

整数验证的代码实验
Take a look at my recent article, hope it could give you some direction:
Code Experiment on Integer Validation


这篇关于同时尝试捕获JAVA验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆