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
程序工作正常,但现在我要采取一切,包括用户输入输出,并将该输出到文件中。
我已经看到了与BufferedWriter
和FileWriter
这样做的方法,我理解这些如何使用阅读器的输入和输出。
除了在我所见过的示例程序,没有这些程序的有方法。
我可以重写我的程序没有方法或修改它们,而不是返回的是void,并且使用System.println
输入。但我想知道是否有办法将我的程序的所有输出发送到文件而不必重写我的程序?