写一个方法void triangle(int a,int b,int c),判断三个参数是否能构成一个三角形。如果不能则抛出异常IllegalArgumentException,显示异常信息:“a,b,c不能构成三角形”;如果可以构成则显示三角形三个边长。在主方法中得到命令行输入的三个整数,调用此方法,并捕获异常。(输入不匹配异常抛出InputMismatchException,非法数据异常抛出IllegalArgumentException。) 输入输出说明: 2 4 3 三角形的三边长为:2,4,3
时间: 2024-02-19 19:03:13 浏览: 46
好的,以下是实现该方法的 Java 代码:
```
import java.util.InputMismatchException;
public class Triangle {
public static void triangle(int a, int b, int c) {
if (a + b <= c || a + c <= b || b + c <= a) {
throw new IllegalArgumentException(a + "," + b + "," + c + "不能构成三角形");
} else {
System.out.println("三角形的三边长为:" + a + "," + b + "," + c);
}
}
public static void main(String[] args) {
try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = Integer.parseInt(args[2]);
triangle(a, b, c);
} catch (InputMismatchException e) {
System.out.println("输入不匹配异常:" + e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println("非法数据异常:" + e.getMessage());
}
}
}
```
在命令行中输入三个整数,如下所示:
```
java Triangle 2 4 3
```
运行结果为:
```
三角形的三边长为:2,4,3
```
如果输入非法的三角形边长,如下所示:
```
java Triangle 1 2 3
```
运行结果为:
```
非法数据异常:1,2,3不能构成三角形
```
如果输入不匹配的参数,如下所示:
```
java Triangle 2 4 a
```
运行结果为:
```
输入不匹配异常:For input string: "a"
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)