Java:从文件中读取整数数组

发布于 2024-12-08 19:32:26 字数 1451 浏览 1 评论 0原文

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

我认为我正在做一些完全错误的事情。请帮忙。

Say i have a file called "input.txt" that has a bunch of positive integers in it:

6
5
6
8
6
2
4

and so on....(one integer per line)

I want to read this file and make it into an array. The first integer (in this case 6) tells the number of indexes or elements in the array, so 6 spots. The other numbers fill in the array starting at 0. So at index 0, the number is 5, at index 1 the number is 6, and so on.

Can someone please show me how to read this file and make it into an array called A and return the integers in each index as n?

this is what i have so far:

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;
}

I think i'm doing something completely wrong. please help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

勿忘心安 2024-12-15 19:32:26

使用扫描器Scanner.nextInt() 方法,只需几行即可解决此问题:

Scanner s = new Scanner(new File("input.txt"));
int[] array = new int[s.nextInt()];
for (int i = 0; i < array.length; i++)
    array[i] = s.nextInt();

Using a Scanner and the Scanner.nextInt() method, you can solve this in just a few lines:

Scanner s = new Scanner(new File("input.txt"));
int[] array = new int[s.nextInt()];
for (int i = 0; i < array.length; i++)
    array[i] = s.nextInt();
苍风燃霜 2024-12-15 19:32:26

Java 8+

int[] ints = Files.lines(Paths.get("input.txt"))
                  .mapToInt(Integer::parseInt).toArray();

Java 8+

int[] ints = Files.lines(Paths.get("input.txt"))
                  .mapToInt(Integer::parseInt).toArray();
余生一个溪 2024-12-15 19:32:26

我认为你需要这个来参加类似 ACM 的比赛:)我使用以下模板:

import java.io.*;
import java.util.*;      

public class Task {

    private BufferedReader input;
    private PrintWriter output;
    private StringTokenizer stoken;

    String fin = "input";
    String fout = "output";


    private void solve() { // some solving code...
        int n = nextInt();
        int[] mas = new int[n];
        for (int i = 0; i<n; i++){
            mas[i] = nextInt();
        }
    }



    Task() throws IOException {
        input = new BufferedReader(new FileReader(fin + ".txt"));
        output = new PrintWriter(new FileWriter(fout + ".txt"));

        solve();

        input.close();
        output.flush();
        output.close();
    }


    int nextInt() {
        return Integer.parseInt(nextToken());
    }


    long nextLong() {
        return Long.parseLong(nextToken());
    }


    double nextFloat() {
        return Float.parseFloat(nextToken());
    }


    double nextDouble() {
        return Double.parseDouble(nextToken());
    }


    String nextToken() {
        while ((stoken == null) || (!stoken.hasMoreTokens())) {
            try {
                String line = input.readLine();
                stoken = new StringTokenizer(line);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stoken.nextToken();
    }


    public static void main(String[] args) throws IOException {
        new Task();
    }

}

在solve()方法中,你可以看到如何读取一个数字N(以下数字序列的长度),然后在循环中(0..N)我从输入中读取整数(在本例中输入是一个文件)。

I think you need this for ACM-like competitions:) I use following template:

import java.io.*;
import java.util.*;      

public class Task {

    private BufferedReader input;
    private PrintWriter output;
    private StringTokenizer stoken;

    String fin = "input";
    String fout = "output";


    private void solve() { // some solving code...
        int n = nextInt();
        int[] mas = new int[n];
        for (int i = 0; i<n; i++){
            mas[i] = nextInt();
        }
    }



    Task() throws IOException {
        input = new BufferedReader(new FileReader(fin + ".txt"));
        output = new PrintWriter(new FileWriter(fout + ".txt"));

        solve();

        input.close();
        output.flush();
        output.close();
    }


    int nextInt() {
        return Integer.parseInt(nextToken());
    }


    long nextLong() {
        return Long.parseLong(nextToken());
    }


    double nextFloat() {
        return Float.parseFloat(nextToken());
    }


    double nextDouble() {
        return Double.parseDouble(nextToken());
    }


    String nextToken() {
        while ((stoken == null) || (!stoken.hasMoreTokens())) {
            try {
                String line = input.readLine();
                stoken = new StringTokenizer(line);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stoken.nextToken();
    }


    public static void main(String[] args) throws IOException {
        new Task();
    }

}

In solve() method you can see how to read one number N (length of the following number sequence) and after that in loop (0..N) I read integers from input (in this case input is a file).

自在安然 2024-12-15 19:32:26
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class filee{
    public static void main(String[] args) throws FileNotFoundException {
        File f = new File("l.txt");
        Scanner b = new Scanner(f);
        int[] arr = new int[b.nextInt()];
            for(int i = 0; i < arr.length; i++){
                arr[i] = b.nextInt();
            }
        for (int o : arr){
            System.out.println(o);
        }
    }
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class filee{
    public static void main(String[] args) throws FileNotFoundException {
        File f = new File("l.txt");
        Scanner b = new Scanner(f);
        int[] arr = new int[b.nextInt()];
            for(int i = 0; i < arr.length; i++){
                arr[i] = b.nextInt();
            }
        for (int o : arr){
            System.out.println(o);
        }
    }
}
牵强ㄟ 2024-12-15 19:32:26

如果文件是classpath资源:

int[] ints = Files
            .lines(Paths.get(ClassLoader.getSystemResource("input.txt")
                    .toURI())).mapToInt(Integer::parseInt).toArray();

打印文件中的内容:

 Arrays.stream(ints).forEach(System.out::println);

If file is a classpath resource:

int[] ints = Files
            .lines(Paths.get(ClassLoader.getSystemResource("input.txt")
                    .toURI())).mapToInt(Integer::parseInt).toArray();

Printing the content from file:

 Arrays.stream(ints).forEach(System.out::println);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文