如何找到文件的行数并将数字输入到Java中的数组大小?

时间:2014-12-08 23:21:01

标签: java arrays loops count java.util.scanner

这是一个相对简单的问题,但由于某种原因我被困了一个小时。我犯的是什么愚蠢的错误?请帮忙!

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Program2 {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(new File("numbers.txt"));

        int count = 0;
        while (scanner.hasNext()) {
            count ++;
            scanner.nextLine();
        }
        int[] array = new int[count];
        for (int i = 0; i < array.length; i++) {
            array[i] = scanner.nextInt();
        }
        for (int i = array.length - 1; i >= 0; i--) {
            System.out.println(array[i]);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

哦......我不得不两次扫描文件-..- FML ......

答案张贴:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Program2 {
    public static void main(String[] args) throws FileNotFoundException {

        Scanner scanner = new Scanner(new File("numbers.txt"));

        int count = 0;
        while (scanner.hasNext()) {
            count ++;
            scanner.nextLine();
        }

        Scanner scanner1 = new Scanner(new File("numbers.txt"));

        int[] array = new int[count];
        for (int i = 0; i < array.length; i++) {
            array[i] = scanner1.nextInt();
        }
        for (int i = array.length - 1; i >= 0; i--) {
            System.out.println(array[i]);
        }
    }
}

答案 1 :(得分:0)

我不太熟悉使用Scanner,我更喜欢用户BufferReader。在这里,我的代码,让我们看看它是否对解决您的问题很有用。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

public class CoountingLines {

    public static void main(final String[] args) throws FileNotFoundException {

        final BufferedReader br = new BufferedReader(new FileReader(new File("/Volumes/nuquer/work/numbers.txt")));
        String line;

        Integer count = 0;
        final HashMap<Integer, String> map = new HashMap<Integer, String>();
        try {
            while ((line = br.readLine()) != null) {
                map.put(count, line.toString());
                count++;
            }

            final int[] array = new int[count];
            for (int i = 0; i < array.length; i++) {
                array[i] = new Integer(map.get(i));
            }

            for (int i = array.length - 1; i >= 0; i--) {
                System.out.println(array[i]);
            }

        } catch (final IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}