【发布时间】:2014-02-23 13:57:05
【问题描述】:
我正在尝试编写满足以下输出的构造函数和方法,但开始时遇到问题。
4.9
20.0
0
false
4.9' person with $20.00 and 0 tickets
4.9' person with $20.00 and 3 tickets
4.9' person with $20.00 and 1 tickets
4.9' person with $20.00 and a pass
这是测试代码:
public class Person2Tester
{
public static void main(String args[])
{
Person mary;
mary = new Person(4.9f, 20.00f);
System.out.println(mary.height);
System.out.println(mary.money);
System.out.println(mary.ticketCount);
System.out.println(mary.hasPass);
System.out.println(mary); // Notice the money is properly formatted
mary.ticketCount = 3;
System.out.println(mary);
mary.useTickets(2); // You have to write this method
System.out.println(mary);
mary.hasPass = true;
System.out.println(mary);
}
}
这是我目前的代码:
public class Person
{
float height;
float money;
int ticketCount;
boolean hasPass;
public Person()//empty constructor
{
height = 0.0f;
money = 0.0f;
ticketCount = 0;
hasPass = false;
}
public Person(float h, float m)
{
height = h;
money = m;
ticketCount = 0;
hasPass = false;
}
public String toString()
{
return(this.height + " person with " + this.money + " and " + this.ticketCount + " tickets");
}
}
这是我完成的代码。感谢所有提供帮助的人。
public String toString()
{
if(hasPass)
{
return(this.height + "' person with $" + this.money + " and has a pass");
}
else
{
return(this.height + "' person with $" + this.money + " and " + this.ticketCount + " tickets");
}
}
public void useTickets(int numTickets)
{
if(this.ticketCount >= numTickets)
{
this.ticketCount -= numTickets;
}
}
【问题讨论】:
-
您的构造函数没有参数,并且在测试中您传递了 2 个参数。那甚至不应该编译。
-
提示:不要在
Person类中重复声明变量 -
我的老师说我们应该总是放置一个参数为零的构造函数@HugoSousa
-
也许你的老师应该学编织。
-
你已经定义了一个没有参数的构造函数,是的。但是您在测试中使用 2 个参数调用它。您尚未声明任何带有 2 个参数的构造函数,因此不应编译。
标签: java object methods boolean drjava