Separate information in a file and read them

I have a text file:

Jim Webb 27 Axelrod Street
Hillary Sanders 92 California Street
Bernie Trudeau 46 Pot Street
Barack Bush 883 White Ave
Mary Warren 736 Something Rd
Donald Crump 65 Debate Street

I need to make out people, name, surname and address (information after the names of persons).

This is my attempt:

public Parse() {
        parseFiles();
    }

    void parseFiles() {
        try {
            File file = new File("school.txt");
            Scanner sc = new Scanner(file);

            while (sc.hasNextLine()) {
                String s = sc.nextLine();
                String[] splited = s.split("\\s+");
                for (int i = 0; i < splited.length; i++) {
                    System.out.println(splited[i]);
                }
            }

        } catch (FileNotFoundException e) {
            System.out.println("File not found\n");
        }

    }

}

Unfortunately, my method analyzes each individual space of a space by a space, which works for the first and last name, but does not work for the address, since I want the address to be a whole string, and not a bunch of strings separated by spaces.

For instances, I have a student class:

public Student(String name, String lastName, String address) {
this.name = name
//etc... 
}

Where do I want to initialize the student each time (read after each line), but with my implementation I can only do this for persons and surnames, how can I parse a separate address separately? You can then call the Student Designer.

+4
2

.next() .nextLine() , :

String firstName = sc.next();
String lastName = sc.next();
String address = sc.nextLine();
+4

, , . if for:

for (int i = 0; i < splited.length; i++) {
    if(i >= (splited.length - 2)) {
        System.out.println(splited[i] + " " + splited[i + 1]);
        break;
    } else
        System.out.println(splited[i]);
}

(splited.length - 2):

for (int i = 0; i < (splited.length - 2); i++) {
    System.out.println(splited[i]);
}
System.out.println(splited[splited.length - 2] + " " + splited[splited.length - 1]);
+2

Source: https://habr.com/ru/post/1616902/


All Articles