假设我有一个名为“input.txt”的文件,其中包含一堆正整数:
6
5
6
8
6
2
4
依此类推....(每行一个整数)
我想读取这个文件并将其放入数组中。第一个整数(在本例中为 6)表示数组中索引或元素的数量,即 6 个点。其他数字从 0 开始填充数组。因此,在索引 0 处,数字为 5,在索引 1 处,数字为 6,依此类推。
有人可以告诉我如何读取这个文件并将其放入名为 A 的数组中并将每个索引中的整数返回为 n 吗?
这是我到目前为止所拥有的:
import java.io.*;
public class inputFile {
public static jobScheduleRecursive(int[] A, int i)
{
try
{
FileReader filereader = new FileReader("input.txt");
BufferedReader bufferedreader = new BufferedReader(filereader);
String line = bufferedreader.readLine();
//While we have read in a valid line
while (line != null) {
//Try to parse integer from the String line
try {
System.out.println(Integer.parseInt(line));
} catch (NumberFormatException nfe) {
System.err.println("Failed to parse integer from line:" + line);
System.err.println(nfe.getMessage());
System.exit(1);
}
line = bufferedreader.readLine();
}
}
catch(FileNotFoundException filenotfoundexception)
{
System.out.println("File not found.");
}
catch(IOException ioexception)
{
System.out.println("File input error occured!");
ioexception.printStackTrace();
}
return A;
}
最佳答案
一步一步(我会让你填写实际的代码):
- 将第一个整数(
java.util.Scanner
可用于读取下一个整数)读取到变量(我们称之为numberOfInts
) - 创建一个名为
A
的数组,其中包含numberOfInts
个元素 - 在循环中,从
0
计数到numberOfInts - 1
(使用索引变量i
):- 从文件中读取下一个整数
- 将
A[i]
设置为您刚刚读取的整数
以下是一些引用资料:
http://download.oracle.com/javase/1,5,0/docs/api/java/util/Scanner.html
http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
关于Java从文件中读取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7701348/