簡體   English   中英

從文本文件輸入到數組

[英]Input from text file to array

輸入將是一個文本文件,其中包含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++;

顯然,該列表尚未初始化,但我不知道它的長度是多少。 另外,我不太確定如何做到這一點。 感謝您的任何幫助。

為了澄清輸入,它看起來像:1236654987432165498732165498756484654651321我不知道長度,我只想要單個整數字符,而不是多個。 所以0-9,而不是0-10像我之前不小心說的那樣。

去收集API即ArrayList

ArrayList a=new Arraylist();
while(numInput.ready()){
       a.add(numInput.read());
}

您可以使用List<Integer>而不是int[] 使用List<Integer> ,您可以根據需要添加項目, List將隨之增長。 如果完成,可以使用toArray(int[])方法將List轉換為int[]

1。 使用guava很好地將文件的第一行讀入1個String

readFirstLine

2。 將該String轉換為char數組 - 因為所有數字都是一位數字,所以它們實際上是char

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM