java - 根据用户选择创建新对象

标签 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;
  }
}

最佳答案

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

selected_dog = new  Labrador();

但是,在您的狗和拉布拉多类中,除了默认构造函数之外,您还有其他构造函数。所以,如果你想创建一个具有特定名称和颜色的新拉布拉多犬,你应该这样写:

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

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

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,应用程序可能会崩溃。有一些方法可以防止这种情况发生;)

关于java - 根据用户选择创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36949025/

相关文章:

java - 如何在父自定义对象数组列表中获取自定义对象子列表中的单个项目位置?

c# - 如何在c#中动态设置数组长度

javascript - 使用 switch 语句选择单选按钮时更改 href 值

java - 使用 swt/Jface 改变表中任何特定列的行大小

java - Java继承中 "override abstract methods"可以用 "implement abstract methods"代替吗?

javascript - 是否可以从对象中删除最后一个属性(按字母顺序)?

c# - 使变量成为必需的 - 以逃避 NullReferenceException?

javascript - 输入框功能不起作用

html - 将预定义的文本放入 HTML 表单文本框中

java - 使用 JSch 跳过 Kerberos 身份验证提示