簡體   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