如何将数组内容写入输出文件?
问题描述:
我有一个程序,从具有两个字段,一周中的一天(1-7)和当天的温度的输入文件读取。然后将它们输入到数组(highArray,lowArray)中,并确定每天的高,低,总和平均温度,并将它们写入输出文件。我遇到的问题是如何将我的数组的内容写入我的输出文件。我可以用这行代码写下星期几:myOutput.writeInt(dow);我意识到Output类INT不适用于数组,因此如何写入以将文件内容存档到我的数组中? (highArray,lowArray)下面是我的代码如何将数组内容写入输出文件?
package dow;
import java.util.Arrays;
public class DOW
{
public static void main(String[] args)
{
// INITIALIZATION
InputFile myInput = new InputFile("in.txt");
OutputFile myOutput = new OutputFile("out.txt");
int dow=0;
int temperature = 0;
int[] highArray = new int [8];
int[] lowArray = new int [8];
int[] countArray = new int [8];
int[] totalArray = new int [8];
// initialize array
for (dow = 0; dow <8; dow++)
{
totalArray [dow]= 0;
countArray [dow]= 0;
highArray [dow]= -999;
lowArray [dow]= 999;
}
while (!myInput.eof())
{
dow = myInput.readInt();
temperature = myInput.readInt();
if (temperature > highArray[dow]) // High Per Day
{
highArray [dow] = temperature;
}
if (temperature < lowArray [dow]) // Low Per DAy
{
lowArray[dow] = temperature;
}
countArray [dow] = countArray[dow] +1;
totalArray[dow] = totalArray [dow] + temperature;
System.out.println(dow);
}
System.out.println(Arrays.toString(lowArray));
System.out.println(Arrays.toString(highArray));
System.out.println(Arrays.toString(totalArray));
System.out.println(Arrays.toString(countArray));
//OUTPUT LOOP
for(dow = 1; dow < 8; dow++)
{
outputFile.println(highArray[dow]);
}
myOutput.writeInt(dow);
// myOutput.write(highArray);
// myOutput.writeInt(totalArray);
// myOutput.writeEOL(countArray);
// myOutput.writeInt (temperature);
myOutput.close();
}
}
//END OF MAIN
答
我会强烈建议使用
BufferedReader
和BufferedWriter
代替InputFile
和OutputFile
。作为一个附注,将
int
数组中的所有值初始化为0是微不足道的,因为System.out.print(Arrays.toString(new int[10]));
将打印出全0。int
是Java中的一种原始类型,因此它始终初始化为0并且不能为null
。这也适用于数组。
实施例:
package dow;
import java.util.Arrays;
public class DOW
{
public static void main(String[] args)
{
BufferedReader reader = new BufferedReader(new FileReader("in.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("out.txt"));
int dow = 0;
int temperature = 0;
int[] highArray = new int [8];
int[] lowArray = new int [8];
int[] countArray = new int [8];
int[] totalArray = new int [8];
// initialize array
for (dow = 0; dow <8; dow++)
{
highArray [dow]= -999;
lowArray [dow]= 999;
}
String nextLine;
while ((nextLine = reader.nextLine()) != null && !nextLine.isEmpty())
{
//DO STUFF
}
reader.close();
writer.write(Arrays.toString(highArray));
writer.close();
}
}
这是不'javascript'相关的,因此我除去标签。 'javascript!== java' – Ricky
@Ricky它实际上是'!='而不是'!==':P –
你想要写入文件的数组内容是什么? 'Arrays.toString(highArray)'格式不满足您的需求吗? –