1. (简答题, 50分)
为一个研究所编写一个通用程序,以计算每次运输行驶 1,000 公里所需的时间。众所周知,每个传输的参数是三个整数 A、B 和 C 的表达式。有两种交通工具,Car007和飞机,其中Car007的速度计算公式为A*B/C,飞机的速度计算公式为A+B+C。你需要编写三个类程序,ComputeTime.java,Plane.java,Car007.java和一个接口程序Common.java。要求如果将来添加第三个运输,则不必修改任何以前的程序,只需为新的运输编写程序即可。程序运行如下:从命令行输入计算时间的四个参数。第一个是传输类型,第二个、第三个和第四个参数是整数 A、B 和 C。例如,使用“java ComputeTime Plane 20 30 40”计算 Plane 的时间,使用 “java ComputeTime Car007 007 23 34” 计算 Car45 的时间。如果第三个运输是 Ship,你只需要写 Ship.java 并输入“java ComputeTime Ship 22 33 44”。提示: 充分利用接口的概念,并使用接口的对象作为参数。实例化对象的另一种方法是使用“Class.forName(str).newInstance()”。例如,如果需要实例化 Plane 对象,则只需调用 Class.forName(“Plane”).newInstance()。
请在答案中提交程序代码和程序输出的屏幕截图。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ComputeTime {
private static final int KM_1000 = 1000;
public static void main(String[] args) {
if (args.length != 4) {
System.err.println("输入格式错误,请输入正确的参数");
return;
}
String vehicleType = args[0];
int a = Integer.parseInt(args[1]);
int b = Integer.parseInt(args[2]);
int c = Integer.parseInt(args[3]);
try {
Common vehicle = (Common) Class.forName(vehicleType).newInstance();
vehicle.setProperties(a, b, c);
double speed = vehicle.computeSpeed();
double time = KM_1000 / speed;
System.out.println("行驶1000公里所需的时间为: " + time + " 小时");
} catch (ClassNotFoundException e) {
System.err.println("找不到指定的类");
} catch (InstantiationException | IllegalAccessException e) {
System.err.println("无法实例化对象");
}
}
}
public class Car007 implements Common {
private int a, b, c;
@Override
public void setProperties(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public double computeSpeed() {
return (double) a * b / c;
}
}
public interface Common {
void setProperties(int a, int b, int c);
double computeSpeed();
}
public class Plane implements Common {
private int a, b, c;
@Override
public void setProperties(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public double computeSpeed() {
return a + b + c;
}
}
2. (简答题, 50分)
编写程序 Colorpane.java 以实现以下 GUI 布局。然后向每个按钮添加一个侦听器,以便在按下按钮时,按钮表面的颜色与上面写的名称相同。
请在答案中提交程序代码和程序输出的屏幕截图。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Colorpane {
public static void main(String[] args) {
JFrame frame = new JFrame("Color Pane");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
JPanel panel = new JPanel(new GridLayout(3, 3));
String[] colors = { "bule", "cyna", "green",
"magenta", "orange", "pink",
"red", "write", "yellow"};
Color[] colorValues = {Color.BLUE, Color.CYAN, Color.GREEN, Color.MAGENTA,
Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, Color.YELLOW};
for(int i=0; i<colors.length; i++){
JButton button = new JButton(colors[i]);
int finalI = i;
button.addActionListener(e->button.setBackground(colorValues[finalI]));
panel.add(button);
}
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}