Search code examples
javaarraysdata-files

Storing integers inside a data file into an array Java


I am trying to store integers from a data file into an array. I am using Java Eclipse IDE.

Here is my data file:

(oddsAndEvens.dat)

2 4 6 8 10 12 14
1 2 3 4 5 6 7 8 9
2 10 20 21 23 24 40 55 60 61

Here is my code:

import java.io.File;
import java.util.Arrays;
import java.io.IOException;
import java.util.Scanner;

public class OddsAndEvens {
    public static void main(String[] args) throws IOException {
        Scanner file = new Scanner(new File("oddsAndEvens.dat"));
        int count, num = 0;
        int[] newRay = null;
        while (file.hasNext()) {
            String line = file.nextLine();
            Scanner chop = new Scanner(line);
            count = 0;
            while (chop.hasNextInt()) {
                num = chop.nextInt();
                count++;

                newRay = new int[count];
                int j = 0;
                for (int i = 0; i < count; i++) {
                    newRay[j] = num;
                    j++;
                }
            }
            System.out.println(Arrays.toString(newRay));
        }
    }
}

My output is coming out as this:


[14, 14, 14, 14, 14, 14, 14]
[9, 9, 9, 9, 9, 9, 9, 9, 9]
[61, 61, 61, 61, 61, 61, 61, 61, 61, 61]

What I am looking for is this:

[2, 4, 6, 8, 10, 12, 14]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 10, 20, 21, 23, 24, 40, 55, 60, 61]

How would I turn these sets of numbers on each line from my data file into an array? Is there an easier way to do it?


Solution

  • you can read each line and store it in a string array by splitting it with space and then convert it to integer, here's how you can do it.\

    import java.io.File;
    import java.util.Arrays;
    import java.io.IOException;
    import java.util.Scanner;
    
    public class OddsAndEvens {
        public static void main(String[] args) throws IOException {
            Scanner file = new Scanner(new File("oddsAndEvens.dat"));
            int[] newRay = null;
            while (file.hasNext()) {
                String line = file.nextLine();
                String[] str = line.split("\\s+");
                newRay = new int[str.length];
                for (int i = 0; i < str.length; i++) {
                    newRay[i] = Integer.valueOf(str[i]);
                }
                System.out.println(Arrays.toString(newRay));
            }
        }
    }