繁体   English   中英

Java,如何在try-catch块中声明变量

[英]Java, how to declare a variable inside a try-catch block

因此,我只是在学习Java,并且正在编写一个简单的程序,但是我发现用户可以输入不是int的内容,因此我在网上查找并找到了解决该问题的最佳方法这将是使用try and catch块。 但是,执行此操作后,程序的其余部分给了我一个错误,因为我在该块中声明了一个变量。 那么如何在块内声明该变量?

            try{
              int guessN = guess.nextInt();
            }
            catch(InputMismatchException err){
                  System.out.println(err);
            }
            finally {
                int guessN = guess.nextInt();
            }
            //Location of error
            if(guessN < newN){
                log("Wrong! The number is more than your guess");
            }

没关系,我只是将代码放在try块中,它可以工作XD对不起!

移动声明ouside并在块内进行分配:

            int guessN = 0;
            try{
               guessN = guess.nextInt(); }
            catch(InputMismatchException err){
                  System.out.println(err);
            }
            finally {
                guessN = guess.nextInt();
            }

像这样

       int guessN=0;
       try{
           guessN = guess.nextInt();
        }
        catch(InputMismatchException err){
              System.out.println(err);
        }
        finally {
             guessN = guess.nextInt();
        }
        //Location of error
        if(guessN < newN){
            log("Wrong! The number is more than your guess");
        }

每次打开花括号时,您都在创建一个示波器。 如果要在该范围之外识别变量,则应在此声明(外部)。

您应该在块外声明它:

     int guessN = 0;
     try{
          guessN = guess.nextInt();
        }
        catch(InputMismatchException err){
              System.out.println(err);
        }
        finally {
            guessN = guess.nextInt();
        }
        //Location of error
        if(guessN < newN){
            log("Wrong! The number is more than your guess");
        }

暂无
暂无

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

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