2017-03-01 2 views
1

私は既にJavaで作成したプログラムで、ユーザーの入力を求めるいくつかのメソッドがあります。ファイルへのメソッドを含むjavaプログラムの出力を送信する

これはプログラムです:

static Scanner numberscanner = new Scanner(System.in); 
static Integer[] houses = {0,1,2,3,4,5,6,7}; 

public static void main(String[] args) 
{ 
    askForCrates(); 
    getTotal(); 
    int max = houses[0]; 
    getMin(); 
    getMaxHouse(max); 
    //Display the house number that recycled the most 
} 


//asks for the crates for each specific house number 
public static void askForCrates() 
{ 
    for (int i = 0; i < houses.length; i++) 
    { 
     System.out.println("How many crates does house " + i + " have?") ; 
     Integer crates = numberscanner.nextInt(); 
     houses[i] = crates; 
    } 
} 

//uses a for statement to get the total of all the crates recycled 
public static void getTotal() 
{ 
    //Get total 
    Integer total = 0; 
    for (int i = 0; i < houses.length; i++) 
    { 
     total = total + houses[i]; 
    } 
    System.out.println("Total amount of recycling crates is: " + total); 
} 

//Displays and returns the max number of crates 
public static Integer getMax(Integer max) 
{ 
    for (int i = 0; i < houses.length; i++) 
    { 
     if(houses[i] > max) 
     { 
      max = houses[i]; 
     } 
    } 
    System.out.println("Largest number of crates set out: " + max); 
    return max; 
} 

// gets the house numbers that recycled the most 
// and puts them in a string 
public static void getMaxHouse(Integer max) 
{ 
    ArrayList<Integer> besthouses = new ArrayList<Integer>(); 

    String bhs = ""; 
    for (int i = 0; i < houses.length; i++) 
    { 
     if(houses[i].equals(max)) 
     { 
      besthouses.add(houses[i]); 
     } 
    } 
    for (Integer s : besthouses) 
    { 
     bhs += s + ", "; 
    } 
    System.out.println("The house(s) that recycled " + max + " crates were: " + bhs.substring(0, bhs.length()-2)); 
} 

// gets the minimum using the Arrays function to sort the 
// array 
public static void getMin() 
{ 
    //Find the smallest number of crates set out by any house 

    Arrays.sort(houses); 
    int min = houses[0]; 
    System.out.println("Smallest number of crates set out: " + min); 
} 
} // probably the closing '}' of the class --- added by editor 

プログラムが正常に動作しますが、今、私は、ユーザー入力を含むすべての出力を取得し、ファイルにその出力を載せていきたいと思います。

私はBufferedWriterFileWriterでこれを行う方法を見てきましたが、読者を使って入力と出力をどのように扱うのか理解しています。

私が見たサンプルプログラムを除いて、これらのプログラムにはメソッドがありません。

私のプログラムをメソッドなしで書き直したり、無効にする代わりに入力を返すように修正したり、System.printlnを使用することができます。しかし、自分のプログラムを書き直すことなく、自分のプログラムのすべての出力をファイルに送る方法があるかどうか疑問に思っていましたか?

答えて

0

簡単な方法は、あなたのプログラムを実行することができますように:正しい方法について

java -jar app.jar >> log.out 

編集:

PrintStream ps = new PrintStream("log.out"); 
PrintStream orig = System.out; 
System.setOut(ps); 

そして忘れてはいけない:中

ps.close(); 

末尾

関連する問題