我正在尝试用Java编写一个程序,该程序显示茶的名称,类型,克,浸泡和双重浸泡时间,以练习学习类/对象/方法。
我遇到了错误,希望有人能帮助阐明一些问题。
public class Tea {
private String Name;
private String Type;
private int GramsPerCup;
private int SteepingMinutes;
public Tea()//default constructor, takes no args, must be same name as class
{
}
public Tea(String Name, String Type, int GramsPerCup, int SteepingMinutes)//constructor that takes arguments
{
Name = Name;
Type = Type;
GramsPerCup = GramsPerCup;
SteepingMinutes = SteepingMinutes;
}
public void DoubleSteep() {
int TeaDoubleSteep = SteepingMinutes * 2;
}
public String PrintDetails() {
return "Name: " + Name + "n" + "Type: " + Type + "/n" + "Grams Per Cup: " + GramsPerCup + "n" + "Steeping Time in Minutes: " + SteepingMinutes + "n" + "For dark brew, steep: " + DoubleSteep + " minutes";
}
}
public class Main {
public static void Main(String[] args) {
Tea tea1 = new Tea("Earl Grey", "Black", 3, 5);
tea1.DoubleSteep();
System.out.println(tea1.PrintDetails());
}
}
请善待,我对此很陌生,谢谢!:)
只是一个提示!
您的代码中有多个错误:
第一:
要创建一个新对象,您必须使用new
然后space
然后是类的名称:
Tea tea1 = newTea("Earl Grey", "Black", 3, 5);//wrong
Tea tea1 = new Tea("Earl Grey", "Black", 3, 5);//correct
//---------^^^^------------------------------------------Note that
第二:
要调用另一个类中的方法,您必须使用 className.methodName()
,而不是:
System.out.println(tea1, PrintDetails());
//---------------------^^--------To call a method in another class you have to use dot(.)
请改用这个:
System.out.println(tea1.PrintDetails());
第三:
您在构造函数中分配了错误的值:
public Tea(String Name, String Type, int GramsPerCup, int SteepingMinutes)
{
Name = TeaName;
//----^^^^^^^^--------Thie name is not exist in your method signature
//same to the others
}
您必须使用:
this.Name = Name;