写一个方法void triangle(int a,int b,int c),判断三个参数是否能构成一个三角形。如果不能则抛出异常IllegalArgumentException,显示异常信息:“a,b,c不能构成三角形”;如果可以构成则显示三角形三个边长。在主方法中得到命令行输入的三个整数,调用此方法,并捕获异常。 输入输出说明: 2 4 3 三角形的三边长为:2,4,3 1 2 3 1,2,3不能构成三角形 1 2.0 3 请输入整数作为三角形的边长!
时间: 2024-01-16 18:04:39 浏览: 26
好的,下面是实现该方法的示例代码:
```java
public class TriangleTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入三角形的三边长:");
try {
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
triangle(a, b, c);
} catch (InputMismatchException e) {
System.out.println("请输入整数作为三角形的边长!");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
public static void triangle(int a, int b, int c) throws IllegalArgumentException {
if (a + b <= c || a + c <= b || b + c <= a) {
throw new IllegalArgumentException(a + "," + b + "," + c + "不能构成三角形");
} else {
System.out.println("三角形的三边长为:" + a + "," + b + "," + c);
}
}
}
```
该方法使用了异常处理机制,在方法签名中声明了可能会抛出 IllegalArgumentException 异常。在方法中,如果判断三个参数不能构成三角形,则抛出该异常,并在异常信息中显示无法构成三角形的三个边长。如果可以构成三角形,则输出三个边长。
在主方法中,先使用 Scanner 类获取命令行输入的三个整数,然后调用 triangle 方法,并使用 try-catch 块捕获可能抛出的异常。如果输入的不是整数,则会抛出 InputMismatchException 异常,程序会输出相应的提示信息。如果 triangle 方法抛出了 IllegalArgumentException 异常,则会在 catch 块中输出异常信息。
相关推荐
![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)