【问题标题】:Java, how to declare a variable inside a try-catch blockJava,如何在 try-catch 块中声明变量
【发布时间】:2014-06-23 22:01:39
【问题描述】:

所以我只是在学习java,并且正在编写一个简单的程序,但是我发现用户可以输入不是int的东西,所以我在网上查了一下,发现最好的解决此问题的方法是使用 try 和 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 抱歉!

【问题讨论】:

标签: java try-catch


【解决方案1】:

将声明移到外面并在块内进行赋值:

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

【讨论】:

    【解决方案2】:

    这样做

           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");
            }
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        你应该在块外声明它:

             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");
                }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-26
          • 2016-10-12
          • 2023-03-09
          • 1970-01-01
          • 1970-01-01
          • 2013-02-08
          相关资源
          最近更新 更多