【发布时间】:2017-03-01 01:06:35
【问题描述】:
我有一个我已经用 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。但是我想知道是否有一种方法可以将我的程序的所有输出发送到一个文件而无需重写我的程序?
【问题讨论】:
标签: java filewriter bufferedwriter