First, create a class called Dog that implements the Comparable interface. Dog w
ID: 3823849 • Letter: F
Question
First, create a class called Dog that implements the Comparable interface. Dog will contain a member variable to hold a name, a constructor that sets up the name, and three methods (getName, compareTo, toString). getName returns the member variable, compareTo works as defined by the Comparable interface, and toString returns the name neatly formatted. Second, you'll compare Dogs by their names. Include a main method in Dog that asks the user to input ten names and generates ten Dog objects. A blank name should not be used to create an object. Using the compareTo method, determine first and last dog among them and print them. Do not simply sort the Dog data.
output SER200 HW11 (run) Variables Action Items run Please enter the dog's name or a blank line to quit Fido Please enter the dog's name or a blank line to quit Skippy Please enter the dog's name or a blank line to quit Fuzzy Please enter the dog's name or a blank line to quit Bailey please enter the dog's name or a blank line to quit Max Please enter the dog's name or a blank line to quit First Dog [name Bailey] Last Dog [name-SkippylExplanation / Answer
DogTest.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class DogTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Dog> d = new ArrayList<Dog>();
for(;;){
System.out.println("Please enter the dog's name or blank line to quit: ");
String name = scan.nextLine();
if(name == null || name.trim().equals("")){
break;
}
else{
d.add(new Dog(name));
}
}
Collections.sort(d);
System.out.println("First: "+d.get(0).toString());
System.out.println("Last: "+d.get(d.size()-1).toString());
}
}
Dog.java
public class Dog implements Comparable<Dog>{
private String name;
public Dog(String make){
this.name = make;
}
public String getName() {
return name;
}
public int compareTo(Dog v)
{
return getName().compareTo(v.getName());
}
public String toString(){
return getClass().getName()+"[name="+getName()+"]";
}
}
Output:
Please enter the dog's name or blank line to quit:
Fido
Please enter the dog's name or blank line to quit:
Skippy
Please enter the dog's name or blank line to quit:
Fussy
Please enter the dog's name or blank line to quit:
Balley
Please enter the dog's name or blank line to quit:
Max
Please enter the dog's name or blank line to quit:
First: Dog[name=Balley]
Last: Dog[name=Skippy]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.