我是java的初学者,我试图解决下面的程序,但是得到错误,谁能告诉我我在哪里做错了?
public class TestGlass
{
public static void main(String [] args)
{
Glass milk = new Glass(15); // 15 ounces of milk
Glass juice = new Glass(3); // 3 ources of juice
milk.drink(2);
milk.drink(1);
milk.report();
juice.fill(6); // went from 3 to 9 ounces
juice.drink(1); // now down to 8 ounces
juice.report();
juice.spill();
juice.report();
}
}
class Glass
{
int ounce;
public void spill()
{
ounce = 0;
}
public void drink(int x){
ounce = ounce-x;
}
public void fill(int x){
ounce = ounce+x;
}
public int getOunce()
{
return ounce;
}
public void report()
{
int x = getOunce();
System.out.println("Glass has " + x + " ounces");
}
}
这是错误,
TestGlass.java:5: error: constructor Glass in class Glass cannot be applied to given types;
Glass milk = new Glass(15); // 15 ounces of milk
^
required: no arguments
found: int
reason: actual and formal argument lists differ in length
TestGlass.java:6: error: constructor Glass in class Glass cannot be applied to given types;
Glass juice = new Glass(3); // 3 ources of juice
^
required: no arguments
found: int
reason: actual and formal argument lists differ in length
2 errors
答案 0 :(得分:1)
您需要向Glass
添加一个接受ounce
参数的构造函数。
class Glass {
....
public Glass (int ounce) {
this.ounce = ounce;
}
....
}
构造函数是使用new
运算符时调用的方法。它的工作是初始化 - 创建 - 类的对象实例。具有一个或多个参数的构造函数(如此构造函数)被设置为接收值以初始化类的实例变量。
注意错误消息是如何提到构造函数的。这是因为如果你没有指定自己的构造函数,Java会添加一个不接受任何参数的默认构造函数。当你调用new
时,默认的no-arg构造函数就被调用了。由于您将参数传递给no-arg构造函数,因此您收到了错误。一旦添加了自己的构造函数,默认的无参数构造函数就会消失。如果你想要一个no-arg版本(例如将ounce
设置为0
或者设置为默认值),你可以通过指定它和我给你的那个来恢复它 - 你可以重载构造函数(参见下面的链接)。
class Glass {
....
public Glass () {
this.ounce = 1;
/* In this setup, a glass always has at least 1 ounce */
/* If you want it be 0, you could say this.ounce = 0, or */
/* just leave everything inside {} blank, since ounce will */
/* default to 0 anyway */
}
public Glass (int ounce) {
this.ounce = ounce;
}
....
}
调用new Glass()
会调用第一个no-arg构造函数。调用new Glass(15)
将调用第二个构造函数,即带参数的构造函数。
Here's a nice tutorial关于构造函数。
关于重载构造函数的答案 1 :(得分:0)
你需要为Glass创建一个带参数的构造函数。
class Glass {
int ounce;
public Glass(int ounce) {
this.ounce = ounce;
}
public void spill()
{
ounce = 0;
}
public void drink(int x){
ounce = ounce-x;
}
public void fill(int x){
ounce = ounce+x;
}
public int getOunce()
{
return ounce;
}
public void report()
{
int x = getOunce();
System.out.println("Glass has " + x + " ounces");
}
}