Sam Welch
Sam Welch

Reputation: 53

Input from text file to array

The input will be a text file with an arbitrary amount of integers from 0-9 with NO spaces. How do I populate an array with these integers so I can sort them later?

What I have so far is as follows:

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

Obviously theList isn't initialized, but I don't know what the length will be. Also I'm not too sure about how to do this in general. Thanks for any help I receive.

To clarify the input, it will look like: 1236654987432165498732165498756484654651321 I won't know the length, and I only want the single integer characters, not multiple. So 0-9, not 0-10 like I accidentally said earlier.

Upvotes: 0

Views: 214

Answers (3)

dantuch
dantuch

Reputation: 9293

1 . Use guava to nicely read file's 1st line into 1 String

readFirstLine

2 . convert that String to char array - because all of your numbers are one digit lengh, so they are in fact chars

3 . convert chars to integers.

4 . add them to list.

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

prints: [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]

Upvotes: 0

Biswajit
Biswajit

Reputation: 2516

Going for Collection API i.e. ArrayList

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

Upvotes: 2

mthmulders
mthmulders

Reputation: 9705

You could use a List<Integer> instead of a int[]. Using a List<Integer>, you can add items as desired, the List will grow along. If you are done, you can use the toArray(int[]) method to transform the List into an int[].

Upvotes: 0

Related Questions