从数组中读取Java数组

use*_*024 2 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;
}
Run Code Online (Sandbox Code Playgroud)

Foo*_*Bah 5

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

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