Reference no: EM13165145
The assignment is to write a program that creates Pet objects from data read from the keyboard. Store these objects into an instance of ArrayList. Then sort the Pet objects into alphabetic order by pet name, and finally display the data in the sorted Pet objects on the screen...
I have written this code to read the Pet objects from the keyboard and store them in a list but I cannot figure out how to display them alphabetically by pet name??
Here is the code so far:
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Pet{
private String name;
private int age;
private double weight;
public Pet(){
}
public Pet(String name, int age, double weight){
setPet(name, age, weight);
}
public static void main(String[] args){
ArrayList<Pet> list = new ArrayList<Pet>();
Scanner console = new Scanner(System.in);
System.out.print("Welocme.\nStart Typing the data of the pets.\n\n");
String loopConditon = "y";
while(loopConditon.equalsIgnoreCase("y")){
String name = "";
int age = 0;
double weight = 0.0;
try{
System.out.printf("Enter name of the pet : ");
name = console.next();
System.out.printf("Enter age of the pet : ");
age = console.nextInt();
System.out.printf("Enter wieght of the pet : ");
weight = console.nextDouble();
Pet mypet = new Pet(name,age,weight);
list.add(mypet);
System.out.print("Do you want to add data of another pet ? (Y/N) : ");
loopConditon = console.next();
System.out.println();
}
catch(IllegalArgumentException e){
System.out.println(e.getMessage());
System.out.println("Discarding the current pet details. Try Again");
}
catch(InputMismatchException e){
System.out.println("Input is not in correct format");
System.out.println("Discarding the current pet details. Try Again");
console.next();
}
}
System.out.println("Input Terminated\n");
System.out.println("The Pet Details are : \n");
for(int i=0; i < list.size(); i++){
System.out.println(list.get(i));
}
}
public void setPet(String name, int age, double weight)
{
setName(name);
setAge(age);
setWeight(weight);
}
public void setName(String name)
{
this.name = name;
}
public void setAge(int age){
if(age <= 0)
throw new IllegalArgumentException("Error : Illegal Age");
this.age = age;
}
public void setWeight(double weight){
if(weight <= 0)
throw new IllegalArgumentException("Error : Illegal weight");
this.weight = weight;
}
public String toString(){
return String.format("Name : %s\nAge: %d\nWeight : %.2f\n",
name,age,weight);
}
}