2013-04-26 25 views
-2

我不明白爲什麼我在main中初始化數組時出錯。我從變量t中刪除了一個變量,並從鍵盤上獲得了它的值。但是當我嘗試初始化一個數組n []用尺寸T,它示出了一個error.plz幫助運行時初始化java中的數組

import java.io.*; 
import java.math.BigInteger; 

class smallfac 
{ 
    static BigInteger fac(BigInteger x) 
    { 
     BigInteger z; 
     if(x.equals(new BigInteger("1"))) 
      return x; 
     else 
     { 
      z=x.multiply(fac(x.subtract(new BigInteger("1")))); 
      return(z); 
     } 
    } 

    public static void main(String args[]) 
    { 
     InputStreamReader in=new InputStreamReader(System.in); 
     BufferedReader br=new BufferedReader(in); 
     try{ 
      int t=Integer.parseInt(br.readLine()); 
     }catch(IOException e){} 
     int[] n=new int[t]; 
     for(int i=0;i<n.length;i++) 
     { 
      try 
      { 
       n[i]=Integer.parseInt(br.readLine()); 
      }catch(IOException e){} 
     } 
     for(int i=0;i<n.length;i++) 
     { 
      int x=n[i]; 
      BigInteger p = new BigInteger(Integer.toString(x)); 
      p=smallfac.fac(p); 
      System.out.println(p); 
     } 
    } 
} 

回答

2

我看到了幾個問題:

try{ 
    int t=Integer.parseInt(br.readLine()); 
}catch(IOException e){} 

int[] n=new int[t]; 

兩個問題有:

  1. t僅在try塊內聲明。它在該塊之外是超範圍的。因此,在上面最後一行嘗試使用t時出現編譯時錯誤。

  2. 即使通過在塊外聲明t並在塊內初始化它,編譯器也不能確定t具有上一行最後一行的值。可能會拋出異常。所以這是一個錯誤(編譯時錯誤)。

後者,第三個問題(至少):

for(int i=0;i<n.length;i++) 
{ 
    try 
    { 
     n[i]=Integer.parseInt(br.readLine()); 
    }catch(IOException e){} 
} 

這是一個邏輯錯誤。如果您在後面的循環中嘗試使用n[i],則不知道n[i]是否已被實際初始化,因爲您隱藏了異常。對於您所知道的,有一個I/O異常初始化爲n[2],所以n[2]保留默認值null值。如果您稍後嘗試使用它而沒有檢查,則會得到NullPointerException

這是一個真的壞主意捕捉並忽略異常,特別是針對特定的代碼行重複執行它。

這裏有一個最小的,變化是返工的main

public static void main(String args[]) 
{ 
    // Put all the code in one try block 
    try { 
     InputStreamReader in=new InputStreamReader(System.in); 
     BufferedReader br=new BufferedReader(in); 
     int t=Integer.parseInt(br.readLine()); 
     int[] n=new int[t]; 
     for(int i=0;i<n.length;i++) 
     { 
      n[i]=Integer.parseInt(br.readLine()); 
     } 
     for(int i=0;i<n.length;i++) 
     { 
      int x=n[i]; 
      BigInteger p = new BigInteger(Integer.toString(x)); 
      p=smallfac.fac(p); 
      System.out.println(p); 
     } 
    }catch(IOException e){ 
     // Report the error here 
    } 
} 
+0

非常感謝.....這真的很有幫助。 – Akshay 2013-04-26 19:02:22

+0

@ user1869756:不客氣!我很高興幫助! – 2013-04-26 21:45:40

0

int[] n=new int[t]; < - 這裏t必須在範圍限定。您可以將其更改爲:

 int t = 0;//or some default value 
     try{ 
      t=Integer.parseInt(br.readLine()); 
     }catch(IOException e){} 
     int[] n=new int[t]; 
+3

't'必須存在,但不一定是恆定的。 – 2013-04-26 11:16:56

4

這是一個範圍界定問題。您在try塊內聲明int t,但之後嘗試使用t的值,這是不可能的; t只在try內部可見。

+4

幾個問題之一。 :-) – 2013-04-26 11:15:28

0

t在裏面試塊定義。因此其範圍limited to try block。你不能在try塊外面訪問它。在try外面定義它,這樣你的數組初始化就可以訪問它了