你好我有一个叫做拖拉机的整个班级,其中存储了不同的数据,但现在我想创建一个带有零参数构造函数的对象调用拖拉机,但这是我到目前为止的代码及其给出的错误
首先关闭我的Tractor Class,它位于不同的文件中:
import java.util.Scanner;
class Tractor
{
private int RentalRate;
private int RentalDays;
private int VehicleID;
private int RentalProfit;
public void setRentalRate(int r)
{
Scanner input = new Scanner(System.in);
System.out.println("What's the Rental Rate?");
int num = input.nextInt();
num = r;
if(r<0 || r >1000)
RentalRate = r;
RentalRate= 1;
}
public int getRentalRate()
{
return RentalRate;
}
public void setVehicleID(int v)
{
Scanner input = new Scanner(System.in);
System.out.println("What's the vehicleID?");
int num1 = input.nextInt();
num1 = v;
if(v<0)
VehicleID = v;
VehicleID = 1;
}
public int getVehicleID()
{
return VehicleID;
}
public void setRentalDays(int d)
{
Scanner input = new Scanner(System.in);
System.out.println("How many rental days?");
int num2 = input.nextInt();
num2 = d;
if(d<0)
RentalDays = d;
RentalDays = 1;
}
public int getRentalDays()
{
return RentalDays;
}
public String toString()
{
String str;
str = "RentalDays:" + RentalDays +"\nRenalRate:" + RentalRate + "\nVehicleID " + VehicleID;
return str;
}
public void RentalProfit(int RentalRate, int RentalDays)
{
RentalProfit = RentalRate * RentalDays;
}
}
import java.util.Scanner;
public class testTractor
{
public static void main(String[] args)
{
public tractor()
{
this.RentalDays = d;
this.RentalRate = r;
this.VehicleID = v;
}
}
}
错误是:
testTractor.java:7: error: illegal start of expression
public tractor()
^
testTractor.java:7: error: ';' expected
public tractor()
^
2 errors
答案 0 :(得分:0)
您有编译错误。您需要先声明Tractor类,然后在其中添加构造函数。一种方法是在单独的文件中声明。除非您已定义d
,否则在Java中也无法分配它。也许您想在下面提供的示例中将日期指定为String
。
您需要首先创建一个文件调用Tractor.java,然后在那里定义变量。例如Tractor.java
的内容:
public class Tractor {
String rentaldays,someOtherValue;
public Tractor(){
rentaldays ="monday";
someOtherValue="value";
}
//or
public Tractor(String rentalDays){
this.rentaldays = rentalDays;
someOtherValue = "asf";
}
}
然后在您的主要方法中您也可以Tractor trac = new Tractor();
或Tractor trac = new Tractor("tuesday");
之后使用trac
System.out.println(trac.rentaldays);
的租借日
从外观上看,你可能会制造拖拉机租赁系统。在这种情况下,rentalDays可能是一系列字符串。然后你会有一系列Tractor对象存储在租赁系统中。您可以查看这些术语和关键字,为您指明正确的方向。
答案 1 :(得分:0)
你定义错了,在class中定义你的方法然后在main()方法中调用它们。
class Test{
public void greeting(){
System.out.print("hello to JAVA..");
}
public static void main(String[] args){
Test testObj = new Test();
testObj.greeting();
}
}
答案 2 :(得分:0)
public class TestTractor(){
Tractor objTractor;
public static void main(String[] args){
//create new tractor object with no parameter
objTractor = new Tractor();
//create new tractor object with parameter
objTractor = new Tractor(parameter here);
//do some action of object here
...........
}
}
答案 3 :(得分:0)
//这只是一个示例
在您的拖拉机类中添加以下代码
public tractor()
{
this.RentalDays = d;
this.RentalRate = r;
this.VehicleID = v;
}
将TestTractor类保持为
public class TestTractor(){
public static void main(String[] args){
Tractor objTractor = new Tractor();
// objTractor.yourMethodName
}
}