下面这个是题目:
为某研究所编写一个通用程序,用来计算每一种交通工具运行1000公里所需的时间,已知每种交通工具的参数都是3个整数ABC的表达式。现有两种工具:Car007和Plane,其中Car007的速度运算公式为A*B/C,Plane的速度运算公式为:A+B+C。需要编写三个类:ComputeTime.java,Plane.java,Car007.java和接口Common.java,要求在未来如果增加第3种或多种交通工具的时候,不必修改以前的任何程序,只需要编写新的交通工具的程序。其运行过程如下,从命令行输入ComputeTime的四个参数,第一个是交通工具的类型,第二、三、四个参数分别是整数A、B、C,举例如下:
计算Plane的时间:"java ComputeTime Plane 20 30 40"
计算Car007的时间:"java ComputeTime Car007 23 34 45"
如果第3种交通工具为Ship,则只需要编写Ship.java,运行时输入:"java ComputeTime Ship 22 33 44"
提示:1、实例化一个对象的另外一种办法:Class.forName(str).newInstance();例如需要实例化一个Plane对象的话,则只要调用Class.forName("Plane").newInstance()便可。
2、注意分析程序中有可能产生的异常,根据需要进行异常捕获和处理。
接下来是我的代码,关于名字之类的我涂掉了。
这个是我的工程结构
package VehicleSystem;
import java.util.Scanner;
public class ComputeTime {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name= String.valueOf(sc.next());
double A = sc.nextInt();
double B = sc.nextInt();
double C = sc.nextInt();
double v, t;
Common d = null;
d = (Common) Class.forName("VehicleSystem."+name).getDeclaredConstructor().newInstance();
v=d.Speed(A,B,C);
t=1000/v;
System.out.println("平均速度为:"+v+"km/h");
System.out.println("运行时间为:"+t+"h");
}
}
这个是接口
package VehicleSystem;
public interface Common {
double Speed(double a, double b, double c);
}
下面两个是其他的类
package VehicleSystem;
public class Plane implements Common{
public double Speed(double a,double b,double c){
double v = a + b + c;
return v;
}
}
package VehicleSystem;
public class Car007 implements Common{
public double Speed(double a,double b,double c){
double v=a*b/c;
if(c==0){
System.out.println("除数为0,输入有误。");
return 0;
}
else{
return v;
}
}
}
麻烦帮忙看看了,谢谢!🙏🏻🙏🏻
以下是实现题目要求的三个类和一个接口的代码:
Common.java:
public interface Common {
double computeTime(int a, int b, int c);
}
```java
Plane.java:
```java
public class Plane implements Common {
@Override
public double computeTime(int a, int b, int c) {
return a + b + c;
}
}
Car007.java:
public class Car007 implements Common {
@Override
public double computeTime(int a, int b, int c) {
return a * b / (double) c;
}
}
ComputeTime.java:
public class ComputeTime {
public static void main(String[] args) {
if (args.length < 4) {
System.out.println("Usage: java ComputeTime <vehicleType> <A> <B> <C>");
return;
}
String vehicleType = args[0];
int a = Integer.parseInt(args[1]);
int b = Integer.parseInt(args[2]);
int c = Integer.parseInt(args[3]);
Common vehicle = null;
try {
vehicle = (Common) Class.forName(vehicleType).newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
System.out.println("Invalid vehicle type: " + vehicleType);
return;
}
double time = vehicle.computeTime(a, b, c);
System.out.println("Time for " + vehicleType + " to run 1000 km: " + (1000 / time) + " hours");
}
}
以上代码中,ComputeTime类是程序的入口,根据命令行参数指定的交通工具类型和参数,动态创建对应的交通工具对象,并调用其computeTime方法计算每一种交通工具运行1000公里所需的时间。
你可以根据需要自行修改代码,添加新的交通工具类。在添加新的交通工具类时,只需要实现Common接口,并在命令行参数中指定对应的交通工具类型即可。
能不能直接贴代码,方便复制运行