221k views
5 votes
Consider the following class definition.

public class Person
{
private String name;
private int feet;
private int inches;
public Person(String nm, int ft, int in)
{
name = nm;
feet = ft;
inches = in;
}
public int heightInInches()
{
return feet * 12 + inches;
}
public String getName()
{
return name;
}
public String compareHeights(person other)
{
if (this.heightInInches() < other.heightInInches())
{
return name;
}
else if (this.heightInInches() > other.heightInInches())
{
return other.getName();
}
else return "Same"
}
}
The following code segment appears in a method in a class other than Person.
Person andy = new Person("Andrew", 5, 6);
Person ben = new Person("Benjamin", 6, 5);
System.out.println(andy.compareHeights(ben));
What, if anything, is printed as a result of executing the code segment?
A. Andrew
B. Benjamin
C. Same
D. Nothing is printed because the method heightInInches cannot be called on this.
E. Nothing is printed because the compareHeights method in the Person class cannot take a Person object as a parameter.

User Paval
by
7.8k points

1 Answer

3 votes

Final answer:

Executing the code segment where 'andy' compares their height with 'ben' using the compareHeights method, will result in the name "Andrew" being printed because andy is shorter than ben.

Step-by-step explanation:

The question concerns the execution of a code segment involving a compareHeights method in a Person class that compares the height of two Person objects. To understand the output, we must first calculate the height in inches of each Person object:

  • Person andy has a height of 5 feet 6 inches, which converts to 66 inches (5*12 + 6).
  • Person ben has a height of 6 feet 5 inches, which converts to 77 inches (6*12 + 5).

According to the compareHeights method, if this Person's height is less than other Person's height, it returns this Person's name. Otherwise, it returns the other Person's name. If both are equal, it returns "Same".

After evaluating the heights, the output of System.out.println(andy.compareHeights(ben)); will be:

"Andrew"

since andy is shorter than ben.

User BennoDual
by
7.4k points