简体   繁体   中英

How to split different data types in String[] in Java

I would appreciate if someone could help me with my school project. I have a txt file with names and phone numbers (ex. John Smith 1123456789). I need Java to read the file and load it into two separate array strings: one with first/last names and another with phone numbers. Please give me advise on how to do it right. Thanks a lot in advance.

         String book;
         FileReader reader;
         BufferedReader buffer;
         String line;
         String[] list;

    try {
        reader = new FileReader(book);
        buffer = new BufferedReader(reader);
        list = new String[50];
        int x = 0;
        line = buffer.readLine();
        while (line != null){
            list[x] = line;
            line = buffer.readLine();
            x++;
        }
        buffer.close();
    } catch(FileNotFoundException e)

If you split the line as follows -

String[] fields = line.split("\\s+"); // \\s+ means one or more space(s)

the result array fields will have 3 elements -

  1. first name at index 0
  2. last name at index 1
  3. phone number at index 2

Currently, you don't seem to have the 2 arrays for storing the names and phones. Create those too, and populate them after every split.

I'm assuming that names/phone numbers on each line are in the same order. I'm also assuming (since this is a school project) that you know which separator is used between the names and the phone numbers. After reading the line, you can split it by using String.split using the separator. The two resulting parts will be the name and phone number, like this:

line = buffer.readLine();
String[] parts = line.split("\t"); // if tab is used as the separator
String name = parts[0];
String phoneNumber = parts[1];

The approach is to create two ArrayList , split the line using String.split() and then insert them in the Lists.

List<String> names = new ArrayList<>();
List<String> phoneNumbers = new ArrayList<>();
while (line != null){
    String[] lineArray = line.split(" ");
    names.add(lineArray[0]);
    phoneNumbers.add(lineArray[1]);
}
String[] namesArray = (String[]) names.toArray();
String[] phoneNumberArray = (String[]) phoneNumbers.toArray();

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