简体   繁体   中英

Scanner for input file and storing data objects from input file in array

Basically, I had to create a scanner for a given file and read through the file (the name is input through the terminal by the user) once counting the number of lines in the file. Then after, I had to create an array of objects from the file, of the correct size (where the num of lines comes in). Then I had to create another scanner for the file and read through it again, storing it in the array I created. And lastly, had to return the array in the method.

My problem is I cannot seem to get the second scanner to actually store the file objects in the array.

I've tried using .nextLine inside a for loop that also calls the array, but it doesn't seem to be working.

public static Data[] getData(String filename) {

            Scanner input = new Scanner(new File(filename));
            int count = 0;
                while (input.hasNextLine()) {
                input.nextLine();
                count++;
                } 
                System.out.println(count);

         Data[] data = new Data[count]; 
         Scanner input1 = new Scanner(new File(filename));          
           while (input1.hasNextLine()) {
                for (int i = 0; i < count; i++) {
                    System.out.println(data[i].nextLine);
                } 
            } 
         return data;
  }

I expect the output to successfully read the input file so that it can be accessed by other methods that I have created (not shown).

Not clear what Data.class do you mean, if you switch it to String, the problem obviously would be in this line

System.out.println(data[i].nextLine);

if you want to assign and print simultaneously write this

 for (int i = 0; i < count; i++) {
     data[i] = input1.next();
     System.out.println(data[i]);
 }

and dont forget to close your Scanners, better use try-with-resources . If your Data is your custom class you'd better learn about Serialization-Deserialization Or use some ObjectMapper-s(Jackson, for example) to store your class instances and restore them.

Your way of opening the file just to count the lines and then again looping through its lines to store them in the array is not that efficient, but it could be just a school assignment.
Try this:

public static Data[] getData(String filename) {
    Scanner input = null;
    try {
        input = new Scanner(new File(filename));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return null;
    }
    int count = 0;
    while (input.hasNextLine()) {
        input.nextLine();
        count++;
    }
    input.close();
    System.out.println(count);

    Data[] data = new Data[count];
    try {
        input = new Scanner(new File(filename));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return null;
    }
    for (int i = 0; i < count; i++) {
        Data d = new Data(input.nextLine(), 0, 0);
        data[i] = d;
        System.out.println(data[i].name);
    }
    input.close();
    return data;
}

After the 1st loop you must close the Scanner and reopen it so to start all over from the first line of the file.

You should definitely use an IDE if you don't have one, try intellij... There you have autocompletion and syntax checking and much more.

It is not clear what you want to do in your for loop, because there are several mistakes, for example the readline() function works only with the scanner objekt, so you can do input.nextline() or input1.nextline()`...

so I just show you, how you can get the Data from a file with Scanner:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class Readfile {

    public static void getData(String filename) throws FileNotFoundException {

        ArrayList<String> test = new ArrayList<>(); //arraylist to store the data

        Scanner inputSc = new Scanner(new File(filename)); //scanner of the file

        while (inputSc.hasNextLine()) {
            String str = inputSc.nextLine();
            System.out.println(str); //print the line which was read from the file
            test.add(str); //adds the line to the arraylist
            //for you it would be something like data[i] = str; and i is a counter
        }
        inputSc.close();

    }

    public static void main(String[] args) {

        try {
            getData("/home/user/documents/bla.txt"); //path to file
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}

You don't need to read thru the file twice - just use an ArrayList to hold the data that's coming in from the file, like this, and then return Data[] at the end:

public static Data[] getData(String filename) {
     List<Data> result = new ArrayList<>();
     try (Scanner input = new Scanner(new File(filename))){
        while (input.hasNextLine()) {
            Data data = new Data(input.nextLine());
            result.add(data);
        } 
     }

     return result.toArray(new Data[0]);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM