2017-07-04 43 views
0

我有一個try-catch的小問題。從Try-Catch中獲取字符串

我的目標是讓testtest2的值超出我稍後可以使用的try塊。

如何處理?

public class MyApplication { 
    public static void main(String[] args) { 
     try { 
      int test = Integer.parseInt("123"); 
      String test2 = "ABCD"; 
     } catch (NumberFormatException ex) { 
      System.out.print(ex.getMessage()); 
     } 
    } 
} 
+3

您有範圍問題並將聲明移出嘗試。 –

+0

在另一個範圍聲明,例如類 – XtremeBaumer

+0

@terades:請爲用戶駱駝案例變量名稱。所有大寫字母都保留給最終變量/常量。 –

回答

4

你寫道:

.... ,我以後可以 ....

使用

這取決於後面的意思,如果你的意思是後來在同一個會議上HOD那麼這樣做:

public static void main(String[] args) { 
    String test2 = ""; 
    try { 
     int test = Integer.parseInt("123"); 
     test2 = "ABCD"; 
    } catch (NumberFormatException ex) { 
     System.out.print(ex.getMessage()); 
    } 
} 

那麼你可以使用的方法類似

test2.isEmpty() 

檢查字符串中的內容進行了更新,ABCD或不...

如果你的意思是後來,但在另一種靜態方法,然後做。

public class MyApplication { 
    static String test2 = ""; 
    public static void main(String[] args) { 
     try { 
      int test = Integer.parseInt("123"); 
      test2 = "ABCD"; 
     } catch (NumberFormatException ex) { 
      System.out.print(ex.getMessage()); 
     } 
    } 
} 
+0

謝謝你生病了試一試:) –

+0

哎!我看到你對這個問題的編輯。請等下一次刪除「謝謝」。 +1 –

+0

馬赫ich:D //我會 –

4

在外部範圍只是宣佈他們:

public class MyApplication { 

    public static void main(String[] args) { 
     int test = Integer.MAX_VALUE; // setting to max value to check if it was set later 
     String test2 = null; 

     try { 
      test = Integer.parseInt("123"); 
      test2 = "ABCD"; 
     } catch (NumberFormatException ex) { 
      System.out.print(ex.getMessage()); 
     } 
    } 
} 
+0

謝謝先生! :) –

+0

我想我現在明白了..當我首先聲明TEST和TEST2時,try函數將這些值設置爲「xxx」並結束,然後我可以稍後使用這些值或?:) –

+0

將TEST初始化爲'Integer.MAX_VALUE',這樣你就可以檢查它是否被設置。如果它初始化爲0,則無法判斷它是默認值還是剛剛設置的值(不適用於123!= 0這種特殊情況)。 – StephaneM

0

正如其他人指出的那樣,您有範圍問題意味着變量Test和Test 2在try-catch塊中聲明。因爲這些,你不能在try-catch塊外部訪問這個變量。有幾種方法可以解決這個問題,最簡單的方法是在主函數聲明或類聲明之後聲明。

public class MyApplication { 

    public static void main(String[] args) { 
     int TEST = 0; 
     String TEST2 = ""; 

     try { 
      TEST = Integer.parseInt("123"); 
      TEST2 = "ABCD"; 
     } catch (NumberFormatException ex) { 
      System.out.print(ex.getMessage()); 
     } 
    } 
} 
+0

謝謝! :)很好解釋! –