0

I try to convert a file to an array of integers, do not know where my mistake is that when I print the array empty array throws

I leave my method , thanks you

public int[] ConvertToArray(File xd) throws IOException {     

 String sCadena;int i=0;
    int[]array;
    FileReader fr = new FileReader(xd); 
    BufferedReader bf = new BufferedReader(fr);
    int lNumeroLineas = 0;
    while ((sCadena = bf.readLine())!=null) {
        lNumeroLineas++;
    }
    array = new int[lNumeroLineas];
    while ((sCadena = bf.readLine())!=null) {
        lNumeroLineas++;
        array[i]=Integer.parseInt(sCadena);
        i++;
    }

    for (int j = 0; j < array.length; j++) {
        System.out.println(array[i]);
    }
    return array;
}

2 Answers 2

1

You are already at the end of file after your first while loop completes.

So reading from BufferedReader object bf again after first while loop ends will always give you null(End of file) and second iteration will never run.

Also in the for loop you are printing array[i] however for loop is iterating over j variable

You can do it like this with help of ArrayList:

public int[] ConvertToArray(File xd) throws IOException {     

 String sCadena;

    ArrayList<Integer> array = new ArrayList();

    FileReader fr = new FileReader(xd); 
    BufferedReader bf = new BufferedReader(fr);
    int lNumeroLineas = 0;
    while ((sCadena = bf.readLine())!=null) {
        lNumeroLineas++;
        array.add(Integer.parseInt(sCadena.trim())); //always recomended to trim(); to remove trailing whitespaces.
    }

    for (int j = 0; j < array.size(); j++) {
        System.out.println(array.get(j));
    }
    return covertIntegers(array);
}

Edited: If you want to send int[] instead of ArrayList<Integer> without using any external libraries.

    public static int[] convertIntegers(List<Integer> integers)
{
    int[] ret = new int[integers.size()];
    for (int i=0; i < ret.length; i++)
    {
        ret[i] = integers.get(i).intValue();
    }
    return ret;
}
Sign up to request clarification or add additional context in comments.

2 Comments

In accordance to what ? Do you want to return an integer array from the above method?
Glad to help ! Please accept the answer if your problem is solved, as it helps everyone who visits this question in future.
0

You are reading the file with two loops but open only once. Reopen the file reader before the second while and it will work.

1 Comment

@ZbynekThank you very much for your contribution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.