gpt4 book ai didi

Java程序报错

转载 作者:行者123 更新时间:2023-12-01 12:09:43 26 4
gpt4 key购买 nike

我是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

最佳答案

您需要向 Glass 添加一个构造函数来接受您的 ounce 参数。

class Glass {
....
public Glass (int ounce) {
this.ounce = ounce;
}
....
}

构造函数是使用 new 运算符时调用的方法。它的工作是初始化(创建)类的对象实例。具有一个或多个参数的构造函数(如本例)被设置为接收值以初始化类的实例变量。

请注意错误消息如何提到构造函数。这是因为,如果您不指定自己的构造函数,Java 会添加一个不接收参数的默认构造函数。当您调用 new 时,会调用默认的无参数构造函数。由于您将参数传递给无参数构造函数,因此出现了错误。添加自己的构造函数后,默认的无参数构造函数就会消失。如果您也想有一个无参数版本(例如,将 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() 将调用第一个无参数构造函数。调用 new Glass(15) 将调用第二个构造函数,即带有参数的构造函数。

Here's a nice tutorial关于构造函数。

Here's a nice tutorial关于重载构造函数。

关于Java程序报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27335794/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com