0

I have a file "input.txt", which has 4 lines of input.

I want to store all the data from line one to one array; second line to another array and so on for the other two.

Here is the example of the file

1 2 3 4 5 6 7 8 9 10 0

3 5 6

4

5 7

i have tried this

Scanner s = new Scanner(new File("input.txt"));
int[] array = new int[s.nextInt()];

for (int i = 0; i < array.length; i++)
    array[i] = s.nextInt();
Mayur Tolani
  • 1,118
  • 2
  • 14
  • 26
  • This is not any site where you post your questions and get your code !! Please try coding yourself and let us know when you get stuck anywhere for help. – Patrick Sep 24 '16 at 20:34
  • Check out the available examples before posting a question !! Few examples for your reference. File reading : http://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java Storing values to Array : http://stackoverflow.com/questions/19400958/java-array-storing-values – Patrick Sep 24 '16 at 20:36
  • @Pat i have posted my trial code, but it does not serve me.your help would be really appriciated – Mayur Tolani Sep 24 '16 at 20:43
  • First read a line - from the file to the scanner and then get the integers 1 by 1 (either by using another scanner or by splitting the string line with delimitor (" ") - space ) store the values into the first array & repeat readline for each array – Patrick Sep 24 '16 at 20:49

1 Answers1

0

First of all, I would recommend using ArrayList. You do not need to know the size of the array while you are creating it. Below you can see my proposition solving your problem. It is more flexible than you requested because it can read more than four lines. We will need the list of integer lists.

    List<ArrayList<Integer>> listOfIntegerLists = new ArrayList<ArrayList<Integer>>();
    Scanner scanner = new Scanner(new InputStreamReader(System.in));
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        Scanner lineScanner = new Scanner(line);
        ArrayList<Integer> list = new ArrayList<Integer>();
        while (lineScanner.hasNextInt())
            list.add(scanner.nextInt());
        if (list.size() != 0)
            listOfIntegerLists.add(list);
    }
Wojciech Kazior
  • 1,208
  • 8
  • 15
  • this looks good, but how do get them into a array, after I have them in a arrayList, my remaining code has input parameters in functions as Arrays. @kazior – Mayur Tolani Sep 24 '16 at 21:47
  • To convert an ArrayList to an array write `Integer[] array = arrayList.toArray(new Integer[arrayList.size()]);`. Vote up if my answer helped! – Wojciech Kazior Sep 25 '16 at 07:18