【发布时间】:2014-12-09 10:13:10
【问题描述】:
我正在尝试将来自不同方法的 2 个数组和一个整数带入写入文件的方法中。我尝试使用参数引入,但它不起作用。希望能帮到你
这就是我从保存数组信息的方法传递参数的方式。
write (NameX, ScoresArray, players); /
该方法旨在使用传递的数组参数来创建文件。
public static void write (String NameX [], int ScoresArray [], int players ) throws IOException
{
PrintWriter outputStream = new PrintWriter(new FileWriter("Genius.txt"));
outputStream.println(players);
for (int i = 0; i < NameX.length; i++)
{
outputStream.println(NameX[i] + ScoresArray [i] );
}
outputStream.close();
}
这是读取文件的方法
public static void reads () throws IOException
{
BufferedReader inStream = new BufferedReader(new FileReader("Genius.txt"));
// Read in first file entry as an integer - the number of names stored
int players = Integer.parseInt(inStream.readLine());
System.out.println(players);
// Create an array big enough
String [] NameX = new String[players];
String [] ScoresArray = new String[players];
// Now read in the names
for (int i = 0; i < NameX.length; i++)
{
NameX[i] = inStream.readLine();
ScoresArray[i] = inStream.readLine();
System.out.println(NameX[i]);
System.out.println(ScoresArray[i]);
}
inStream.close();
}
请您告诉我哪里出了问题以及如何创建一个文件来保存数组并稍后读取文件。
******************修改后的代码********************
write(NameX,ScoresArray,players);
reads();
}
}//end of league table
public static void write (String NameX [], int ScoresArray [], int players ) throws IOException
{
PrintWriter outputStream = new PrintWriter(new FileWriter("Genius.txt"));
outputStream.println(players);
for (int i = 0; i < NameX.length; i++)
{
outputStream.println(NameX[i] +":"+ ScoresArray [i] );
}
outputStream.close();
} public static void reads() 抛出 IOException { BufferedReader inStream = new BufferedReader(new FileReader("Genius.txt"));
// Read in first file entry as an integer - the number of names stored
int players = Integer.parseInt(inStream.readLine());
System.out.println(players);
// Create an array big enough
String [] NameX = new String[players];
String [] ScoresArray = new String[players];
// Now read in the names
for (int i = 0; i < NameX.length; i++)
{
String str = inStream.readLine();
String vals[] = str.split(":");
System.out.println(vals[0]+" "+vals[1]);
}
inStream.close();
}
我仍然遇到同样的问题
【问题讨论】:
-
您面临什么问题,您是否遇到任何异常......等等。
-
它说未报告的 IOException:必须捕获或显示才能抛出。错误是针对我调用 write 方法并传递数组的行。
-
实际上,您正在处理我发生检查异常的文件。 Java doc 说您必须为已检查的异常提供异常处理。所以把 try-catch 块放在你初始化类并对文件执行读/写操作的地方,然后检查输出,让我知道进一步的问题。