我有一个我已经用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
该程序运行正常但现在我想获取包括用户输入在内的所有输出并将该输出放入文件中。
我已经看到了使用BufferedWriter
和FileWriter
执行此操作的方法,我了解它们如何使用阅读器处理输入和输出。
除了我见过的示例程序外,这些程序都没有方法。
我可以在没有方法的情况下重写我的程序,或者修改它们以返回输入而不是无效并使用System.println
。但我想知道是否有办法将我的程序的所有输出发送到文件而不必重写我的程序?
答案 0 :(得分:0)
简单的方法是,您可以将程序运行为:
java -jar app.jar >> log.out
以正确的方式编辑:
PrintStream ps = new PrintStream("log.out");
PrintStream orig = System.out;
System.setOut(ps);
别忘了:
ps.close();
最后