Array of Objects Concept Problem in Java

Problem:

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 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 a tab character. Then, after the input has been read in, print the list in an appropriate format to the screen.


Output:

Lewis Lotfus 5302
WinXP isGood 3324
Bill Gates 3245
Kyle Skill 3234
Lewis     Lotfus     5302
WinXP     isGood     3324
Bill      Gates      3245
Kyle      Skill      3234

Solution:

import java.util.Scanner;
public class Problem2
{
  private String first;
  private String last;
  private int zip;
  
  public Problem2(String first, String last, int zip)
  {
    this.first = first;
    this.last = last;
    this.zip = zip;
  }
  
  public String toString()
  {
    return first + "\t" + last + "\t" + zip + "\t";
  } 
  public static void main (String[] args)
  {
    Scanner scan = new Scanner (System.in);
    Problem2[] prb2 = new Problem2[4];
    for (int i=0;i<prb2.length;i++)
    {
      prb2[i] = new Problem2 (scan.next(),scan.next(),scan.nextInt());
    }
    
    for (int i=0;i<prb2.length;i++)
    {
      System.out.println(prb2[i]);
    }
  }
}

1 comment: