Design and implement an application (name the driver class Part3) that reads a s
ID: 3922736 • Letter: D
Question
Design and implement an application (name the driver class Part3) that reads a sequence of up to 25 pairs of names and postal codes for individuals from a file named activity1.inp (E.g. each line of the data file should contain a person's name and a standard 5 digit zip code). Read in the data from the input file and store the data in an object designed to store a first name (string), last name (string) and postal code (integer). Assume each line of input will contain two strings followed by an integer value, each separated by white space. Your data should be stored in a Person class that you design that contains a default (no argument) constructor, accessors and mutators for all data, and a toString method used in the printing. After the input has been read in, use a for loop to iterate through the 25 objects and print the String representation of each data object by calling your toString method for the class that stores the data. You are required to create your own input file and to include it in the jar file you will use to deliver your lab. Your program should work though with any input file following the described format. Use an array of Person objects to store the data objects.Explanation / Answer
Hi friend please find my code.
Input file contains:
each line: first_name last_name zip_code
Note: zip_code shoud be of type integer
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class PersonObjectProgram {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// asking for input file name
System.out.print("Enter input filename: ");
String fileName = sc.next();
// opening input file name
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
// creating Array to Store Person Object
Person[] persons = new Person[25];
String line;
int index = 0;
while(((line = br.readLine()) != null) && index<25){
// splitting line by space
// if empty line, then stop
if(line.trim().equals("") || line.trim().isEmpty())
break;
String[] temp = line.split("\s+");
// creating a person object
Person p = new Person();
p.setFirstName(temp[0]); // first element of temp array : first name
p.setLastName(temp[1]);
p.setZipCode(Integer.parseInt(temp[2].trim()));
// adding in array list
persons[index++] = p;
}
//closing file
br.close();
fr.close();
// printing array list
for(Person p : persons){
System.out.println(p.toString());
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.