用Java写代码:某高速公路限速120公里/小时,编写程序并使用异常处理超速。 (1)定义超速异常类OverSpeedException抛出超速提示信息。 (2)定义Monitor类,定义方法measureSpeed(double speed),如果速度speed超过120,该方法将抛出OverSpeedException异常。 (3)定义测试类ExcepitonTest,在main方法中随机产生汽车行驶速度speed,并调用measureSpeed(double speed)方法测试是否超速。
时间: 2024-03-22 16:41:44 浏览: 33
好的,以下是Java代码实现:
OverSpeedException.java
```
public class OverSpeedException extends Exception {
public OverSpeedException(String message) {
super(message);
}
}
```
Monitor.java
```
public class Monitor {
public void measureSpeed(double speed) throws OverSpeedException {
if (speed > 120) {
throw new OverSpeedException("超速警告:当前车速超过限制!");
}
}
}
```
ExceptionTest.java
```
import java.util.Random;
public class ExceptionTest {
public static void main(String[] args) {
Monitor monitor = new Monitor();
Random random = new Random();
double speed = random.nextDouble() * 200; // 随机产生速度,最大为200
try {
monitor.measureSpeed(speed);
System.out.println("当前车速为:" + speed + " 公里/小时,未超速!");
} catch (OverSpeedException e) {
System.out.println(e.getMessage());
}
}
}
```
该程序会随机产生一个速度值并调用`measureSpeed`方法,如果超速则会抛出`OverSpeedException`异常并输出异常信息,否则会输出当前车速未超速。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)