Sabuha Kaya
Sabuha Kaya

Reputation: 17

Java Reading a txt that has different numbers in its column file and store data in an arraylist

Hello Guys I have a txt file below, I need to store the second column data but it gives me an error since some lines have 1 some have 2 and some have 3 input in each line. How can I solve that problem?


5
3 4
3 4
3 3
3 4
3 3
3 4
3 3
3 2
3 4
3 3
3 2
3 1
3 4
3 3
3 2
3 1
3 0
1
2
5 3 4
3 4
3 4
3 3
3 4
3 3
3 4
3 3
3 2
3 4
3 3
3 2
3 1
3 4
3 3
3 2
3 1
3 0
1
2
5 4 6
4 4
4 4
4 4
4 4
4 4
4 4
4 3
4 3
4 3
4 3
4 4
4 4
1
2
5 4 6
0

Here is what I did, I tried to differentiate as the size and in the other way but still cant get the answer...

String line = "";

ArrayList<String> numbers= new ArrayList<String>();

try {

    String sCurrentLine;
    br = new BufferedReader(new FileReader("input1.txt"));
    int n = 0;

    while ((sCurrentLine = br.readLine()) != null) {
        String[] arr = sCurrentLine.split(" ");
        int size = arr.length;

        List<String> list = ConvertToList.convertArrayToList(arr);
        List<Integer> listOfInteger = convert.convertStringListToIntList(list, Integer::parseInt);
        if (list.size() == 2) {
            line.split("\\s+");
            numbers.add(line.split("\\s+")[0]);
            System.out.println(numbers);
        }
    }
} catch(Exception e) {
    e.printStackTrace();
}

Upvotes: 1

Views: 66

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79015

You do not need to split the line again. When you split the line first time, check if the length of the resulting array is 2. If yes, add arr[1] to numbers.

while ((sCurrentLine = br.readLine()) != null) {
    String[] arr = sCurrentLine.split(" ");                
    if (arr.length >= 2) {
        numbers.add(arr[1]);
        System.out.println(numbers);
    }
}

Update:

Based on your comment, I am providing you following code which uses your lists:

while ((sCurrentLine = br.readLine()) != null) {
    String[] arr = sCurrentLine.split(" ");
    List<String> list = ConvertToList.convertArrayToList(arr);
    List<Integer> listOfInteger = convert.convertStringListToIntList(list, Integer::parseInt);
    if (listOfInteger.size() >= 2) {
        numbers.add(listOfInteger.get(1));
    }          
}
System.out.println(numbers);

You can keep System.out.println(numbers); inside or outside the while loop depending on how you want to print numbers.

Upvotes: 2

mohammed ahmed
mohammed ahmed

Reputation: 305

If you want to read and save only the second column than you get the data in second column by using the index 1. (After your while loop.)

String secondCol = sCurrentLine.split(" ")[1];

In case you don't have a value in 2 column than it will throw and exception which you should handle with simple try catch. Finally convert it to int and store in your list. with following.

listOfInteger.add(Integer.parseInt(secoundCol));

Hopefully it will work.

Upvotes: 0

Related Questions