我正在用另一个单独的驱动类做一个类。汽车类别是由汽车租赁公司存储有关汽车的信息,如汽车的制造、型号和登记号码,这样我就可以使用驾驶员类输入新车辆,检查一辆汽车是否出租,是否不可用,如果租用,则检查租用人的姓名。
我的汽车课用的方法:
public class Car {
private String Make;
private String Model;
private int RegistrationNum;
public Car(String Make, String Model, String RegN){
//Constructor,
//stores the make, model and registration number of the new car
//sets its status as available for hire.
Make = "";
Model = "";
RegN = "";
}
public String getMake(){
return Make;
}
public String getModel(){
return Model;
}
public boolean hire(String newHirer){
{
//Hire this car to the named hirer and return true.
return true;
}
//Returns false if the car is already out on hire.
}
public boolean returnFromHire(){
{
//Receive this car back from a hire and returns true.
return true;
}
//Returns false if the car was not out on hire
}
public int getRego(){
//Accessor method to return the car’s registration number
RegistrationNum++;
return RegistrationNum;
}
public boolean hireable(){
//Accessor method to return the car’s hire status.
{
//returns true if car available for hire
return true;
}
}
public String toString(){
//return car details as formatted string
//output should be single line containing the make model and reg number
//followed by either "Available for hire" or "On hire to: <name>"
return "Vehicle ID number: "+ getRego()+"-"+"Make is: "+ getMake()+"-"+"Model is: "+getModel();
}
}以下是我的驾驶课程:
import java.util.*;
public class CarDriver {
static Car car1;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
{
System.out.println("Make?");
String Make=scan.nextLine();
System.out.println("Model");
String Model=scan.nextLine();
System.out.println("Registration number?");
String RegNum=scan.nextLine();
car1 = new Car(Make,Model,RegNum);
System.out.println("What you input :");
System.out.println(car1.toString());
}}
}我的产出:
Make?
carmake
Model
carmodel
Registration number?
12345t
What you input :
Vehicle ID number: 1-Make is: null-Model is: null问题:
。
发布于 2012-04-19 09:32:09
第二位
将构造函数更改为此构造函数:
public Car(String Make, String Model, String RegN){
this.Make = Make;
this.Model= Model;
this.RegN = RegN;
}您以前的构造器有一个问题,基本上您所做的就是获取构造函数参数,并将它们全部设置为"“(空字符串),您不想这样做。要将参数值赋值给实例字段。如果您想访问实例字段,就必须使用关键字这个。
public Car(String Make, String Model, String RegN){
//Constructor,
//stores the make, model and registration number of the new car
//sets its status as available for hire.
Make = "";
Model = "";
RegN = "";}
发布于 2012-04-19 09:59:18
第一:为了检索关于“这辆车是谁租来的”或“哪个司机租了这辆车”的信息,您必须先存储该信息。您会使用什么数据类型?(请记住这是“家庭作业”,我认为最好不要给我答案)。
P.S:对于变量和非静态/最终属性,最好使用非大写标识符。
发布于 2012-04-19 09:37:50
正如我在代码中所看到的,您没有在构造函数中设置Car实例的任何字段。你应该写这样的字:
public Car(String Make, String Model, String RegN){
//Constructor,
//stores the make, model and registration number of the new car
//sets its status as available for hire.
this.Make = Make;
this.Model = Model;
this.RegN = RegN;
}https://stackoverflow.com/questions/10225224
复制相似问题