根据用户选择创建新对象

时间:2016-04-29 23:33:55

标签: java object input

我试图在步骤6中返回创建的狗。

对于第6步,返回创建的狗只是

return selected_dog; 

还是其他什么?因为selected_dog返回错误

这是DogTest类

import java.util.Scanner;

public class DogsTest
{
  private static Scanner input = new Scanner(System.in);

  public static void main(String[] args)
  {
    final String YES = "y";

    String answer;
    Dog my_dog;                          // Step 1

    do
    {
      // ------------------------------------------------------------
      // The compiler cannot know at compile time what type my_dog is
      // so it is determined at runtime every time the loop iterates
      // ------------------------------------------------------------
      my_dog = getDog();
      System.out.println(my_dog.getName() + " says " + my_dog.speak());

      System.out.print("Try again? ");
      answer = input.next();
    } while (answer.equalsIgnoreCase(YES));
  }

  public static Dog getDog()                           // Step 2
  {
    int choice;
    Dog selected_dog;                               // Step 3
    String name,
           color;

    do
    {
      // ----------------------------------
      // A null reference indicates that an
      // invalid menu choice was entered
      // ----------------------------------
      selected_dog = null;
      System.out.print("Choose a Breed (1. Labrador  2. Yorkshire): ");
      choice = input.nextInt();

      switch (choice)
      {
        case 1:  System.out.print("Enter dog's name: ");
                 name = input.next();
                 System.out.print("Enter dog's color: ");
                 color = input.next();
                 selected_dog =   Labrador;  // Step 4
                 break;
        case 2:  System.out.print("Enter dog's name: ");
                 name = input.next();
                 selected_dog = ______;  // Step 5
                 break;
        default: System.out.println("Invalid choice");
                 break;
      }
    } while (selected_dog == null);
    return __________________;                                       // Step 6
  }
}

狗班

public class Dog
{
  protected String name;

  public Dog(String name)
  {
    this.name = name;
  }

  public String getName()
  {
    return name;
  }

  public String speak()
  {
    return "Woof";
  }
}

拉布拉多班

public class Labrador extends Dog
{
  private String color;
  private static int breed_weight = 75;

  public Labrador(String name, String color)
  {
    this.color = color;
  }

  // =========================================
  // Big bark -- overrides speak method in Dog
  // =========================================
  public String speak()
  {
    return "WOOF";
  }

  public static int avgBreedWeight()
  {
    return breed_weight;
  }
}

2 个答案:

答案 0 :(得分:1)

在您已经显示的第一行代码中,您尝试使用"默认构造函数"创建三个对象。那些课程。它会工作,但你错过了括号。它应该是这样的:

selected_dog = new  Labrador();

但是,在你的狗和拉布拉多阶级,除了聋人之外你还有其他建设者。因此,如果您想创建具有特定名称和颜色的新拉布拉多,您应该这样写:

selected_dog = new Labrador("name", "color");

最后一件事。在labrador的构造函数中,您将名称作为参数传递但不使用它。您应该向该构造函数的第一行添加对超类构造函数的调用,如下所示:

public Labrador(String name, String color)
  {
    super(name);
    this.color = color;
  }

我希望我足够清楚:) 快乐学习!

<强>重新编辑:

看一下这段代码并尝试理解它:

DogsTest课程:

public class DogsTest {

    private static final Scanner INPUT = new Scanner(System.in);

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        final String YES = "y";
        final String NO = "n";

        String answer;
        Dog my_dog;                          // Step 1

        do {
            // ------------------------------------------------------------
            // The compiler cannot know at compile time what type my_dog is
            // so it is determined at runtime every time the loop iterates
            // ------------------------------------------------------------
            my_dog = getDog();
            System.out.println(my_dog.getName() + " says " + my_dog.speak());

            do {
            System.out.print("Try again? ");
            answer = INPUT.next();
            } while ( !( answer.equalsIgnoreCase(YES) || answer.equalsIgnoreCase(NO) ) );
        } while (answer.equalsIgnoreCase(YES));
    }

    public static Dog getDog() {
        int choice;
        String name;
        String color;
        boolean loop = true;
        do {
            System.out.print("Choose a Breed (1. Labrador  2. Yorkshire) 3. Cancel: ");
            choice = INPUT.nextInt();
            switch (choice) {
                case 1:
                    System.out.print("Enter dog's name: ");
                    name = INPUT.next();
                    System.out.print("Enter dog's color: ");
                    color = INPUT.next();
                    return new Labrador(name, color);
                case 2:
                    System.out.print("Enter dog's name: ");
                    name = INPUT.next();
                    System.out.print("Enter dog's color: ");
                    color = INPUT.next();
                    return new Yorkshire(name, color);
                case 3:
                    loop = false;
                    break;
                default:
                    System.out.println("Invalid choice");
                    break;
            }
        } while (loop);
        return null;
    }

}

狗班:

public class Dog {

// ====================================================================================================

// DATA STRUCTURE

// Instance data
    private String name;

// Class data
    private static final String DEFAULT_NAME = "No name";

// ====================================================================================================

// CONTRUCTORS

// Complete
    public Dog(String name) {
        this.name = name;
    }

// Default
    public Dog() {
        this.name = DEFAULT_NAME;
    }

// Copy
    public Dog(Dog dogToCopy) {
        this.name = dogToCopy.name;
    }

// ====================================================================================================

// GET
    public String getName() {
        return name;
    }

// ====================================================================================================

// SET
    public void setName(String name) {
        this.name = name;
    }

// ====================================================================================================

// TO STRING
    @Override
    public String toString() {
        return "The dog's name is "+name+". ";
    }

// ====================================================================================================

// FUNCTIONALITIES
    public String speak() {
        return "woof";
    }

// ====================================================================================================

}

拉布拉多班:

public class Labrador extends Dog{

// ====================================================================================================

// DATA STRUCTURE

// Instance data
    private String color;

// Class data
    private static int breedWeight = 75;
    private static final String DEFAULT_COLOR = "No color";


// ====================================================================================================

// CONTRUCTORS

// Complete
    public Labrador(String name, String color) {
        super(name);
        this.color = color;
    }

// Incomplete
    public Labrador(String name) {
        super(name);
    }

// Default
    public Labrador() {
        super();
        this.color = DEFAULT_COLOR;
    }

// Copy
    public Labrador(Labrador labradorToCopy) {
        super(labradorToCopy.getName());
        this.color = labradorToCopy.color;
    }

// ====================================================================================================

// GET
    public String getColor() {
        return color;
    }

// ====================================================================================================

// SET
    public void setColor(String color) {
        this.color = color;
    }

    public static void setBreedWeight(int newBreedWeight) {
        Labrador.breedWeight = newBreedWeight;
    }

// ====================================================================================================

// TO STRING
    @Override
    public String toString() {
        return super.toString()+"The dog's color is "+color+". ";
    }

// ====================================================================================================

// FUNCTIONALITIES
    @Override
    public String speak() {
        return "WOOF";
    }

    public static int avgBreedWeight() {
        return breedWeight;
    }

// ====================================================================================================

}

约克郡班:

public class Yorkshire extends Dog {

// ====================================================================================================

// DATA STRUCTURE

// Instance data
    private String color;

// Class data
    private static int breedWeight = 75;
    private static final String DEFAULT_COLOR = "No color";


// ====================================================================================================

// CONTRUCTORS

// Complete
    public Yorkshire(String name, String color) {
        super(name);
        this.color = color;
    }

// Incomplete
    public Yorkshire(String name) {
        super(name);
    }

// Default
    public Yorkshire() {
        super();
        this.color = DEFAULT_COLOR;
    }

// Copy
    public Yorkshire(Yorkshire yorkshireToCopy) {
        super(yorkshireToCopy.getName());
        this.color = yorkshireToCopy.color;
    }

// ====================================================================================================

// GET
    public String getColor() {
        return color;
    }

// ====================================================================================================

// SET
    public void setColor(String color) {
        this.color = color;
    }

    public static void setBreedWeight(int newBreedWeight) {
        Yorkshire.breedWeight = newBreedWeight;
    }

// ====================================================================================================

// TO STRING
    @Override
    public String toString() {
        return super.toString()+"The dog's color is "+color+". ";
    }

// ====================================================================================================

// FUNCTIONALITIES
    @Override
    public String speak() {
        return "WOOF";
    }

    public static int avgBreedWeight() {
        return breedWeight;
    }

// ====================================================================================================

}

你能理解我做了什么吗? 注意它的方式,如果你不在狗类型选择上写一个int,应用程序可能会崩溃。有办法防止这种情况;)

答案 1 :(得分:0)

好像你忘了输入正确

selected_dog = new  Labrador("Bingo", "White");  

Doe解决了你的问题?