0

输入将是一个文本文件,其中包含从 0 到 9 的任意数量的整数,没有空格。如何使用这些整数填充数组,以便以后对它们进行排序?

到目前为止,我所拥有的如下:

BufferedReader numInput = null;
    int[] theList;
    try {
        numInput = new BufferedReader(new FileReader(fileName));
    } catch (FileNotFoundException e) {
        System.out.println("File not found");
        e.printStackTrace();
    }
    int i = 0;
    while(numInput.ready()){
        theList[i] = numInput.read();
        i++;

显然 theList 没有初始化,但我不知道长度是多少。另外,我不太确定如何做到这一点。感谢我收到的任何帮助。

为了澄清输入,它看起来像:1236654987432165498732165498756484654651321 我不知道长度,我只想要单个整数字符,而不是多个。所以0-9,而不是我之前不小心说的0-10。

4

3 回答 3

2

选择 Collection API 即 ArrayList

ArrayList a=new Arraylist();
while(numInput.ready()){
       a.add(numInput.read());
}
于 2013-04-01T18:54:35.367 回答
0

您可以使用 aList<Integer>而不是 a int[]。使用 a List<Integer>,您可以根据需要添加项目,它List会随之增长。如果完成,您可以使用该toArray(int[])方法将 转换Listint[].

于 2013-04-01T18:56:26.130 回答
0

1. 使用番石榴很好地将文件的第一行读入 1String

读第一行

2. 将该字符串转换为 char 数组- 因为您的所有数字都是一位数长度,所以它们实际上是chars

3. 将字符转换为整数。

4. 将它们添加到列表中。

public static void main(String[] args) {

    String s = "1236654987432165498732165498756484654651321";
    char[] charArray = s.toCharArray();
    List<Integer> numbers = new ArrayList<Integer>(charArray.length);
    for (char c : charArray) {
        Integer integer = Integer.parseInt(String.valueOf(c));
        numbers.add(integer);
    }

    System.out.println(numbers);
}

印刷:[1, 2, 3, 6, 6, 5, 4, 9, 8, 7, 4, 3, 2, 1, 6, 5, 4, 9, 8, 7, 3, 2, 1, 6, 5, 4, 9, 8, 7, 5, 6, 4, 8, 4, 6, 5, 4, 6, 5, 1, 3, 2, 1]

于 2013-04-01T19:04:31.793 回答