[英]How to use toString in this example?
目前正在做一些功课并且遇到了麻烦 - 我不确定如何正确使用 toString 。 这是作业问题:
创建一个名为 Vehicle 的类,作为车辆类型的超类。 Vehicle 类包含车轮数量和每加仑平均英里数的私有变量。 Vehicle 类还包含一个构造函数,该构造函数带有用于表示车轮数和每加仑平均英里数的整数参数,以及一个 display() 方法,该方法使用 toString() 方法打印所需的输出以将整数值转换为 String。
创建两个子类 Car 和 MotorCycle,它们扩展了 Vehicle 类。 每个子类都包含一个构造函数,该构造函数接受每加仑英里数的值作为参数,并强制将车轮数设置为适当的值——2 代表摩托车,4 代表汽车。 使用超类构造函数设置轮子和 mpg 数据字段(使用 super 关键字)。
编写一个 UseVehicle 类来实例化每个子类的一个对象并显示该对象的值。 将文件另存为 Vehicle.java、Car.java、MotorCycle.java 和 UseVehicle.java
public class Vehicle {
protected int wheelnumber;
protected int mpg;
Vehicle (int wheelnum, int aMpg) {
wheelnumber = wheelnum;
mpg = aMpg;
}
public void display() {
System.out.println("Wheels: " + toString(wheelnumber) + " Mpg: " + toString(mpg));
}
}
public class Car extends Vehicle{
Car (int CarMPG) {
super(4, CarMPG);
}
}
public class Motorcycle extends Vehicle{
Motorcycle (int MotorcycleMPG) {
super(2, MotorcycleMPG);
}
}
public class UseVehicle {
public static void main(String[] args) {
Car Car1 = new Car(30);
Motorcycle Motorcycle2 = new Motorcycle(60);
System.out.print("Car--> ");
Car1.display();
System.out.print("Motorcycle—> ");
Motorcycle2.display();
}
}
使用 toString() 方法打印所需的输出以将整数值转换为字符串。
在这句话中,老师指的是Integer.toString()
,参见Integer
类。 可能是重载Integer.toString(int i)
。
有将 integer 转换为 string 的替代方法,其中一些看起来更简单。 但老师要求这种特殊方法可能是有原因的。
这里有几个问题。 一,您的问题说wheelnumber 和mpg 应该是私有的。 其次,数据类型应该是整数。 希望下面能解决你的问题。
public class Vehicle {
//should be private as per question
private Integer wheelnumber;
private Integer mpg;
Vehicle (int wheelnum, int aMpg) {
wheelnumber = wheelnum;
mpg = aMpg;
}
public void display() {
System.out.println("Wheels: " + wheelnumber.toString + " Mpg: " + mpg.toString);
}
}
现在详细说明一下, toString()方法是在JavaObject类中定义的,您默认定义的任何类都会扩展它。
您使用的数据类型 - “int”是一种原始数据类型(直接取自 C - 简单但不是面向对象的方法),它不扩展 JavaObject类。 因此,您不能对原始数据类型的任何实例使用 toString() 方法。
而“ Integer ”数据类型是Java API中定义的一个类,它扩展了Object类并在其中定义了toString()方法。 因此,您可以对此类的任何实例使用 toString() 方法。
话虽如此,如果您绝对必须将“int”变量转换为字符串,我建议您执行以下操作:
int i = 10;
System.out.println("Value of i: " + Integer.toString(i));
请注意, int 或 Integer 可以轻松转换为字符串,而无需调用 toString() 方法,因为当您将它与字符串连接时,Java 会自动为您执行此操作 - 如下所示:
int p = 10;
Integer q = new Integer(20);
System.out.println("value of p:" + p + ", q:" + q);
但是,这不是传统的方式,我猜这不是你老师在这个作业中想要的。
我会在 Vehical 上实现 toString()
public class Vehicle {
protected int wheelnumber;
protected int mpg;
Vehicle (int wheelnum, int aMpg) {
this.wheelnumber = wheelnum;
this.mpg = aMpg;
}
public void display() {
System.out.println(this.toString());
}
@Override
public String toString() {
return "Wheels: " + this.wheelnumber + " Mpg: " + this.mpg;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.