简体   繁体   中英

Read names/phone numbers from text file and store them into an array in java

The problem wants me to complete the code by reading the first four names of the text file and storing it into the array.

Here is the code to fill in.

import java.io.*;
import java.util.Scanner;


public class PersonDemo
{
  public static void main(String[] args)
  {
    File file = new File("phonedata.txt");
    Scanner infile = new Scanner(System.in);
    Person[] pArray = new Person[4];
    for(int i=0;i<4;i++)
    {
      String n = infile.nextLine();
      String p = infile.nextLine();

What am i supposed to be inserting in here?

     }  
     infile.close();

   }
}    

The object file being used is:

public class Person
{
  private String name = "";
  private String phone ="";

public Person(String n, String p)
{
    name = n;
    phone = p;
}

public  Person()
{
    name ="";
    phone="";
}
public void setName(String n)
{
    name =n;
}
public void setPhone(String p)
{
    phone = p;
}
public String getName()
{
    return name;
}
public String getPhone()
{
    return phone;
}
public String toString()
{
    return "Name: "+name + "  Phone: " + phone;
}

}

The text file being used is:

Olivia

555-1111

Tim

555-2222

Theresa

555-3333

Forest

555-4444

Frank

555-5555

Simon

555-6666

Now how am I supposed to use the object file to store the text into the array I am confused on what the code is supposed to look like?

Welcome to Stack Overflow @tristan

After String p = infile.nextline(); , do pArray[i] = n + " " + p

This should make your loop look like:

for(int i=0;i<4;i++)
{
  String n = infile.nextLine();
  String p = infile.nextLine();
  Person person = new Person(n, p); 
  pArray[i] = person;
}

This should do what you are asking for.

You can use this logic :

for (int i = 0; i < 4; i++) {
   String name = infile.nextLine();
   infile.nextLine();               // skip a line because there is a blank line in between
   String phoneNum = infile.nextLine();
   infile.nextLine();               // here again skipping a blank line
   Person per = new Person(name, phoneNum); 
   pArray[i] = per;
} 

Explanation :

  1. Here we store the name and phone number in string variables name and phoneNum .
  2. Now using these variables we create an object of Person using the parameterized constructor.
  3. Next, we assign this object to the corresponding index of the array.

Also your scanner should be defined as below to read the file via your scanner object infile

Scanner infile = new Scanner(file);

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