Design and implement an application that reads a sequence of up to 25 pairs of n
ID: 3700979 • Letter: D
Question
Design and implement an application that reads a sequence of up to 25 pairs of names and postal (zip) codes for individuals. Store the data in an object of a class called “NameAndZip”, designed to store a first name (String), last name (String), and a postal code (int). Create a driver class called “NameAndZipList”. Assume that each line of input will contain two strings followed by an integer value. You will then create an object for each line read in and store that object in an array of NameAndZip objects. After the Names and Codes have been entered, print the list in an appropriate format to the screen using the toString method in the NameAndZip class. To test the program enter 3 names and codes.
Explanation / Answer
import java.util.Scanner;
public class NameAndZipList {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
NameAndZip[] list=new NameAndZip[3];
//read first name.last name and zip code
for (int i = 0; i < 3; i++)
{
System.out.println("Enter first,last name followed by zipcode");
String input=scan.nextLine();
//split by space
String data[]=input.trim().split(" ");
String firstName=data[0];
String lastName=data[1];
int zipcode=Integer.parseInt(data[2]);
list[i]=new NameAndZip(firstName, lastName, zipcode);
}
//print to console
System.out.println("NameAndZip list");
for (int i = 0; i < list.length; i++) {
System.out.println(list[i].toString());
}
}
}
---------------------------------------
//NameAndZip.java
public class NameAndZip {
private String firstName;
private String lastName;
private int zip ;
//Constructor to set first name ,last name and zip code
public NameAndZip(String fName, String lName,
int code) {
firstName=fName;
lastName=lName;
zip=code;
}
/*Override toString method*/
public String toString() {
return String.format("%-10s%-10s%-10d", firstName,lastName,zip);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.