Java 第三次课作业
为某研究所编写一个通用程序,用来计算每一种交通工具运行1000公里所需的时间,已知每种交通工具的参数都是3个整数ABC的表达式。
现有两种工具:Car007和Plane,其中Car007的速度运算公式为A*B/C,Plane的速度运算公式为A+B+C
需要编写三类,ComputeTime.java Plane.java Car007.java 和接口 Common.java
要求在未来如果增加第3种交通工具的时候,不必修改以前的任何程序,只需编写新的交通工具的程序。
其运行过程如下,从命令行输入ComputeTime的四个参数,第一个是交通工具的类型,第二、三、四个参数分别是整数ABC
在chengxu3这个包里
主程序:
package chengxu3;
public class ComputeTime2
{
public static void main(String[] args) //输入的都是字符串
{
System.out.println("交通工具 : " + args[0]);
System.out.println(" 参数 A: " + args[1]);
System.out.println(" 参数 B: " + args[2]);
System.out.println(" 参数 C: " + args[3]);
if(args[1] != null && args[1].matches("^[0-9]+$") && args[2] != null && args[2].matches("^[0-9]+$") && args[3] != null && args[3].matches("^[0-9]+$") )
//判断abc是否是整数
{
double a = Double.parseDouble(args[1]); //把abc换成浮点型数(单位都是km/h)
double b = Double.parseDouble(args[2]);
double c = Double.parseDouble(args[3]);
double v, t; //定义速度、时间
try
{
Common d = (Common) Class.forName("chengxu3."+args[0]).newInstance(); //d为通过chengxu3包里的接口,输入的args[0]
v = d.Velocity(a,b,c); // v = return的值
t = 1000 / v;
System.out.println("平均速度:" + v + " km/h");
System.out.println("运行时间:" + t + " h ");
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) //找不到类 例外 or 实例化 例外 or 非法访问 例外 ???
{
System.out.println("class not found");
}
} // if 括号结束
else
{
System.out.println("不是整数!" + "\n");
} // if - else 结束
}
}
接口:
package chengxu3;
public interface Common
{
double Velocity(double a,double b,double c) ;
}
007的车:
package chengxu3;
public class Car007 implements Common
{
public double Velocity(double a, double b, double c)
{
if(c == 0)
{
System.out.println("除数为0");
return 0;
}
else
return a * b / c;
}
}
灰机:
package chengxu3;
public class Plane implements Common
{
public double Velocity(double a,double b,double c)
{
return a + b + c;
}
}
大船:
package chengxu3;
public class Ship implements Common
{
public double Velocity(double a, double b, double c)
{
return (a + b - c);
}
}
程序就是这么多,下边是怎么用,嗯。我觉得挺清楚的。有错误的话求指正。
过程:
先编一个交通工具的代码比如Plane.java
选中ComputeTime.java右击,运行方式中点击运行配置,自变量选项卡中程序自变量
输入Plane 20 30 40