2016-08-26 4 views
-1

(mainメソッドを呼び出すクラスが)例外7

import java.io.*; 

public class bob { 
public static void main(String[] args){ 
    new bert(); 
    new larry(); 

public class larry{ 
    bert bertObj = new bert(); 
    public larry(){ 
     try{ 
     File file = new File("text.txt"); 

     if(!file.exists()) 
      file.createNewFile(); 
     PrintWriter pw = new PrintWriter(file); 
     for(String x: bertObj.string){ 
     pw.println(x); 
     } 
     pw.close(); 
    }catch(IOException e){ 
     e.printStackTrace(); 
    } 
    } 
} 

は(読み込み(それへのファイルとcopys文字列を作成します)ファイルをコピーして文字列配列にコピーします) (文字列を初期化していないので、エラーではないかと思いますが、その中にいくつの値が格納されているかはわかりません)String string [] = new例えば、String [100] ... else else私が行う)

クラスBERTで
public class bert { 
    String string[]; 
    public bert(){ 
     BufferedReader br = null; 
     try{ 
      br = new BufferedReader(new FileReader("C:\\Program Files\\Java\\jdk1.8.0_101\\THIRDPARTYLICENSEREADME.txt")); 
      int counter = 0; 
      while((string[counter] = br.readLine()) != null) 
      { 
       counter++; 
      } 
      for(int x = counter; x < 4000; x++) 
       string[x] = ""; 
     }catch(IOException e){ 
      e.printStackTrace(); 
     }finally{ 
      try { 
       br.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 
+1

をこれに対する最も簡単な解決策は、配列を取り除くと、ArrayListのか、文字列を使用して取得することです。私はあなたの考えを知りません。(int x = counter; x <4000; x ++) string [x] = ""; 'doは実行します –

答えて

-1

、あなたの文字列を[]に初期化されることはありませんあなたはこの行でそれにアクセスしようとする前に:?

while((string[counter] = br.readLine()) != null) 

ちょうどあなたのようなラリークラスで初期化BERT bertクラスのString []を初期化する必要があります。

電源を入れ、この行:

String [] string; 

の中へは:

String[] string = new String[5]; // 5 is an arbitrary number I chose, you need to choose how many strings you will be holding in that array 

申し訳ありませんが、完全にあなたのコメントを読んでいません。静的な配列の代わりに、arraylistを使ってみてください。これは配列と同じようには動作しません。ここでArrayListの上

ArrayList<String> string = new ArrayList(); 
string.add("hello");  // string now has a string "hello" 
string.add("world");  // string now has a string "hello" followed by a string "world" 

for(int i = 0; i < string.size(); i++) { 
    System.out.println(string.get(i)); // gets position i from the array and prints it. Will print hello then a new line then world. 
} 

より:

あなたに簡単な例を挙げれば

ArrayList API

+0

ありがとう!非常に役に立ちます:) –

+0

問題はありません、私は人々が重複としてマークするとき、私は嫌い、ちょうど質問に答える、これらは時々非常に具体的です! – Cmoraski

関連する問題