Java 在创建一些方法时遇到困难
我目前正在制作一个程序来存储拖拉机租赁数据,我在拖拉机课上遇到了一个问题,我需要覆盖toString方法来打印拖拉机的所有信息,以及计算租金利润的方法,这只是租金天数*租金率,但我得到了这些错误,我不知道从这里开始该怎么办Java 在创建一些方法时遇到困难,java,object,methods,jgrasp,Java,Object,Methods,Jgrasp,我目前正在制作一个程序来存储拖拉机租赁数据,我在拖拉机课上遇到了一个问题,我需要覆盖toString方法来打印拖拉机的所有信息,以及计算租金利润的方法,这只是租金天数*租金率,但我得到了这些错误,我不知道从这里开始该怎么办 public int RentalProfit(int RentalRate, int RentalDays) { RentalProfit = RentalRate * RentalDays; return this.RentalProf
public int RentalProfit(int RentalRate, int RentalDays)
{
RentalProfit = RentalRate * RentalDays;
return this.RentalProfit;
}
@Override
public String toString() {
return "Tractor (Rental days = " + RentalDays + ", Rental Rate = " + RentalRate +
"Rental profit = " RentalProfit + ", VehicleID = " + VehicleID ")";
}
以下是错误:
Tractor.java:59: error: ';' expected
"Rental profit = " RentalProfit + ", VehicleID = " + VehicleID ")";
^
Tractor.java:59: error: not a statement
"Rental profit = " RentalProfit + ", VehicleID = " + VehicleID ")";
^
Tractor.java:59: error: ';' expected
"Rental profit = " RentalProfit + ", VehicleID = " + VehicleID ")";
^
3 errors
public static void main(String[] args){
Tractor tractor;
tractor = new Tractor();
tractor.setRentalRate(9);
tractor.setRentalDays(45);
tractor.setVehicleID(9145949);
toString();
这是一个错误:
testTractor.java:11: error: non-static method toString() cannot be referenced from a static context
toString();
^
1 error
您缺少一个
+
符号:
return "Tractor (Rental days = " + RentalDays + ", Rental Rate = " + RentalRate +
"Rental profit = " + RentalProfit + ", VehicleID = " + VehicleID + ")";
^ ^
here and here
在main方法中,您正在调用
toString()代码>不能这样做-toString不是静态方法,必须通过实例调用。您需要的是tractor.toString()代码>第一个错误返回字符串时,必须像这样关闭它
return ("Tractor Rental days = " + RentalDays + " Rental Rate = " + RentalRate +
"Rental profit = "+ RentalProfit + ", VehicleID = " + VehicleID );
第二个问题
我认为您有main方法,它是静态的,您需要使用make static方法来调用它make the method toString()static。。。
我希望我能帮助你两个缺少的+
:租金利润=“+RentalProfit+”,车辆ID=“+VehicleID+”代码>在主目录中:toString()
应该是tractor.toString()
;即使2,如果你仔细看的话。:-)另一个问题。所以我是我的主要拖拉机类,我正在尝试将这个toString()应用到拖拉机对象中,我应该怎么做呢?是的,我发现现在它给了我这个输出,拖拉机(租赁天数=9145949,租赁费率=0,租赁利润=0,车辆ID=9145949),我不知道为什么它会这样做。