3. 输入三角形的三条边,求三角形面积。当三条边无法构成三角形时进行异常处理。用Java中的try和catch 编程
时间: 2024-05-12 13:16:58 浏览: 15
好的,我了解了你的问题。以下是Java代码实现:
```java
import java.util.Scanner;
public class TriangleArea {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the length of the first side of the triangle: ");
double side1 = input.nextDouble();
System.out.println("Please enter the length of the second side of the triangle: ");
double side2 = input.nextDouble();
System.out.println("Please enter the length of the third side of the triangle: ");
double side3 = input.nextDouble();
try {
double s = (side1 + side2 + side3) / 2;
double area = Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
if (Double.isNaN(area)) {
throw new Exception("The three sides cannot form a triangle!");
}
System.out.println("The area of the triangle is: " + area);
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
}
```
可以看到,程序成功使用了Java中的try和catch机制进行异常处理。用户输入三个长度后,程序首先计算出半周长s,然后用海伦公式求三角形面积。如果面积计算结果为NaN,则抛出一个异常,表示三条边无法构成三角形。如果没有异常,则正常输出三角形的面积。
请问还有其他问题吗?
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)