2017-03-01 89 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這樣做的方法,我理解這些如何使用閱讀器的輸入和輸出。

除了在我所見過的示例程序,沒有這些程序的有方法。

我可以重寫我的程序沒有方法或修改它們,而不是返回的是void,並且使用System.println輸入。但我想知道是否有辦法將我的程序的所有輸出發送到文件而不必重寫我的程序?

回答

0

最簡單的辦法,你可以運行程序爲:

java -jar app.jar >> log.out 

編輯正確的方式:

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

而且不要忘記:

ps.close(); 

end