Consider a software system that models a horse barn. Classes that represent horses implement the following interface.

public interface Horse
{
   /** @return the horse's name */
   String getName();

   /** @return the horse's weight */
   int getWeight();
}

A horse barn consists of N numbered spaces. Each space can hold at most one horse. The spaces are indexed starting from 0; the index of the last space is N – 1. No two horses in the barn have the same name. The declaration of the HorseBarn class is shown below.

Write the HorseBarn method findHorseSpace. This method returns the index of the space in which the horse with the specified name is located. If there is no horse with the specified name in the barn, the method returns -1.

public class HorseBarn
{
   /** The spaces in the barn. Each array element holds a reference to the horse
   * that is currently occupying the space. A null value indicates an empty space.
   */
   private Horse[] spaces;

   /** Returns the index of the space that contains the horse with the specified
    *  name.
    * Precondition: No two horses in the barn have the same name.
    * @param name the name of the horse to find
    * @return the index of the space containing the horse with the specified
    *      name;
    *      -1 if no horse with the specified name is in the barn.
    */
   public int findHorseSpace(String name)
   { /* to be implemented in part (a) */ }
}

如何解题

为了找到同名马的索引,我们需要遍历数组spaces。在循环的过程中,我们需要比较待寻找的名字与Horse object的名字。要记得对null进行特殊处理。



0:00

Which of the following correctly retrieves the name of a “Horse” object from the “spaces” array?

第一级为数组,第二级需要通过method来访问field。
2

一旦我们有了当前Horse object的名字,我们即可进行比较。

What is the best way to compare two strings for equality?

Java中比较两字符串相等的最好方式是equals==只判断引用是否相等。
3

以下是本题的参考答案。

public int findHorseSpace(String name) {
  for (int i = 0; i < this.spaces.length; i++) {
    if (this.spaces[i]!=null && names.equals(this.spaces[i].getName())) {
      return i;
    }
  }
  return -1;
}

陈 欣

AADPS创始人

发表评论