Java从文件中读取数组

标签 java arrays file

假设我有一个名为“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;
}

最佳答案

一步一步(我会让你填写实际的代码):

  1. 将第一个整数(java.util.Scanner 可用于读取下一个整数)读取到变量(我们称之为 numberOfInts)
  2. 创建一个名为 A 的数组,其中包含 numberOfInts 个元素
  3. 在循环中,从 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/

相关文章:

java - 使用 Java 在 pentaho Kettle-spoon 中进行转换和工作的示例程序(Eclipse)

java - 有没有办法在 Java for-each 循环中访问迭代计数器?

java - 当我复制两个空路径时会发生什么并且为什么它不抛出异常?

java - 将库添加到 jar 中

file - 从字符串解析后如何从文件解析?

Java - 删除按钮所在的面板

java - ApachePOI : NoClassDefFoundError : org. apache.poi.openxml4j.exceptions.invalidFormatException

c++ - 插入数组的额外字符

c - 使用数组打印出一些星号,这取决于用户在 C 中输入的数字

C 简单数组代码不起作用