2

Please I will like to adjust this code that reads integers from a file. I will like the code to detect the number (n) of the dataset instead of having to put in figures manually as done below (4000 )

double[] tall = new double[4000];

public class Extracto {

    public static void main(String[] args) throws IOException {

        File fil = new File("C:\\Users\\Desktop\\kaycee2.csv");
        FileReader inputFil = new FileReader(fil);
        BufferedReader in = new BufferedReader(inputFil);
        double[] tall = new double[4000];
        String s = in.readLine();
        int i = 0;
        while (s != null) {
            // Skip empty lines.
            s = s.trim();
            if (s.length() == 0) {
                continue;
            }
            tall[i] = Double.parseDouble(s); // This is line 19.
            //  System.out.println(tall[i]);
            s = in.readLine();
            i++;

        }

I am expecting the adjusted code to obtain the data length without manually putting it in like in as shown in the code below for the 4000 length.

double[] tall = new double[4000];

1
  • Use a list instead of an array Commented Aug 26, 2019 at 16:14

1 Answer 1

3

As Thomas mentioned, use a list, instead of an array.

    File fil = new File("C:\\Users\\Desktop\\kaycee2.csv");
    FileReader inputFil = new FileReader(fil);
    BufferedReader in = new BufferedReader(inputFil);
    ArrayList<Double> tall = new ArrayList<>();
    while(in.ready()){ 
        String s = in.readLine().trim();
        if(!s.isEmpty()){
           tall.add(Double.parseDouble(s);
        } 
    }

your codes can be further compacted if you use a list. also do add a try-catch in the event when the String read is not a number.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much @ Angel

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.