打印Getter方法

时间:2015-11-13 08:30:34

标签: java switch-statement

我尝试在两个不同类的switch语句中打印出Getter方法时遇到问题。模板(甜甜圈)课和巧克力课可以帮助我吗?

public class Donut {
  private boolean sprinkles;
  private String flavor;
  private boolean filled;
  private String frostingFlavor;
  private boolean hole;
  private String name;
  public Donut(String name) {
      this.name=name;
  }
  public void setSprinkles(boolean sprinkles) {
      this.sprinkles=sprinkles;
  }
  public void setFlavor(String flavor) {
      this.flavor=flavor;
  }
  public void setHole(boolean hole) {
      this.hole=hole;
  }
  public void setFilled(boolean filled) {
      this.filled=filled;
  }
  public void frostingFlavor(String frostingFlavor) {
      this.frostingFlavor=frostingFlavor;
  }
  public String Donut() {
      return name;
  }
  public boolean Sprinkles() {
      return sprinkles;
  }
  public String getFlavor() {
      return flavor;
  }
  public boolean Hole() {
      return hole;
  }
  public boolean Filled() {
      return filled;
  }
  public String frostingFlavor() {
      return frostingFlavor;
  }
}

这是班级

import java.io.*;
import java.util.*;

public class Chocolate {
  public static void main(String args[]){
      Donut chocolate=new Donut("chocolate");//Sets donut name to chocolate
      chocolate.setFlavor("chocolate");//sets donut flavor to chocolate
      chocolate.setHole(true);//donut object has a hole
      chocolate.setFilled(false);//donut object isn't filled
      chocolate.frostingFlavor("vanilla");//donut frosting flavor is vanilla
      chocolate.setSprinkles(true);//donut object has sprinkles
      Scanner kbReader=new Scanner(System.in);//scanner/imput header
      System.out.println("What would you like to know?");//start of switch statement
      System.out.println("1. Donut Flavor");
      System.out.println("2. Donut Frosting Flavor");
      System.out.println("3. Donut Sprinkles");
      System.out.println("4. Filled");
      System.out.println("5. Sprinkles");
      System.out.println("6. Donut Hole\n");
      int choice=kbReader.nextInt();
      switch(choice) {
          case 1://Donut Flavor
          System.out.println(Donut.getFlavor());
      }
  }
}

如果有人能帮助我,那真是太棒了,谢谢。

1 个答案:

答案 0 :(得分:1)

因为getFlavor()方法不是静态方法,所以无法做到 Donut.getFlavor()但您必须someDonutObject.getFlavor()。幸运的是,你已经拥有了一个Donut对象,所以你可以choclate.getFlavor()。它必须是这样的,因为你想知道特定甜甜圈的味道,每个甜甜圈可能有不同的味道。如果您的每个甜甜圈的价值相同(例如价格),您可以将其作为静态方法。 还有一件事:通常方法以小写字母char开头,如果方法只返回一个值,通常也会以“get'然后你回来了。您可能希望将Donut()更改为getName()。有时布尔值会有例外,因此Filled()可能会变为isFilled()