2016-12-06 4 views
0

私は基本的に袋を作り、私の袋の1つに少なくとも100000の要素が含まれていなければならないと言われました。これは、Eclipseのコンソールウィンドウに収まりません。情報をファイルに書き込む方が良い考えです。私は主なメソッドとrunBigBadメソッドをここに入れました。ご覧のとおり、runBigBagの後にはもっとやりたいことがあります。コンパイルして正常に動作します。ただし、runBigBag()呼び出しの後のすべてをテキストファイルに出力します。テキストファイルにrunBigBag()の内容を入れ、残りはコンソールウィンドウに出力します。誰かが私を助けることができますか? finally句を使用してps.close()を実行しようとすると、psを初期化してファイルをnullにする必要があります。だから私は簡単な方法がなければ何をすべきか分からない。 setOutを使用してプリントストリームを閉じる

public class TestBag { 

public static <E> void main(String[] args) { 
    //Start time for WHOLE PROGRAM 
    final long start = System.currentTimeMillis(); 
    //Run small bag 
    runSmallBag(); 
    //RESET COUNTERS TO ALLOW BIG BAG TO KEEP TRACK OF COMPLEXITY 
    Bag.resetCounters(); 
    //Run big bag 
    runBigBag(); 
    //Display the operation counters for each method used in whole program 
    System.out.println("Number of times add() was used for whole program: " + Bag.addCountA + "\n"); 
    System.out.println("Number of times remRand() was used for whole program: " + Bag.ranRemCountA + "\n"); 
    System.out.println("Number of times rem() was used for whole program: " + Bag.remCountA + "\n"); 
    System.out.println("Number of times contains() was used whole program: " + Bag.containsCountA + "\n"); 
    System.out.println("number of times addAll() was used whole program: " + Bag.addAllCountA + "\n"); 
    System.out.println("Number of times union() was used whole program: " + Bag.unionCountA + "\n"); 
    System.out.println("Number of times equal() was used whole program: " + Bag.equalsCountA + "\n"); 
    //End timer for whole program 
    final long end = System.currentTimeMillis(); 
    //Display timer for whole program 
    System.out.println("The whole program took " + ((end - start)*.001) + " seconds to run"); 
} 
public static <E> void runBigBag(){ 

    //Start time for big bag operations 
    final long start2 = System.currentTimeMillis(); 

    boolean prog = true; 

    //Create file to write bag too 
    File file = new File("bag.txt"); 
    PrintStream ps; 
    try { 
     ps = new PrintStream(new FileOutputStream(file)); 
     System.setOut(ps); 
    } catch (FileNotFoundException f) { 
     f.printStackTrace(); 
    } finally 
    //irrelevant code here 


    //End timer for big bag 
    final long end2 = System.currentTimeMillis(); 

    //Display timer for big bag 
    System.out.println("This part of the program took " + ((end2 - start2)*.001) + " seconds to run"); 

} 

}

答えて

2

ので、後続のすべてのSystem.outコールがあなたのファイルライタに送信されているデフォルトの出力ストリームを変更しています。そのようなことが起こらないようにするには、ファイルの書き込みにデフォルトの出力ストリームを使用しないでください。

あなたの問題への最も迅速な回答はここにあります。私は、デフォルトのシステム出力とでを使用する別のPrintStreamを作成し

PrintStream ps; 
PrintStream stdout = System.out; 

How do I create a file and write to it in Java?

0

トッシュの答えは、おそらく私のために良い仕事だろうが、私は実際にそれを私は期待していた方法を実行する方法を発見します私はこれはおそらく私が意図していないバックグラウンドで何かを行いますが、私が必要とする出力を与えると確信している

System.setOut(stdout); 

:メソッドの最後には、私が入れ。あなたのご提案ありがとうございます。