用java写三个整数判断是否能构成三角形
时间: 2023-05-12 22:04:31 浏览: 106
可以,以下是代码示例:
```java
public static boolean isTriangle(int a, int b, int c) {
if (a <= 0 || b <= 0 || c <= 0) {
return false;
}
if (a + b <= c || a + c <= b || b + c <= a) {
return false;
}
return true;
}
```
这个方法接受三个整数作为参数,返回一个布尔值,表示这三个整数是否能构成一个三角形。如果能构成三角形,返回 true,否则返回 false。
相关问题
用java实现判断输入的三个数,是否构成三角形
以下是用Java实现判断输入的三个数是否构成三角形的代码:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入第一个整数: ");
int a = scanner.nextInt();
System.out.print("请输入第二个整数: ");
int b = scanner.nextInt();
System.out.print("请输入第三个整数: ");
int c = scanner.nextInt();
boolean isTriangle = isTriangle(a, b, c);
if (isTriangle) {
System.out.println("可以构成三角形");
} else {
System.out.println(a + "," + b + "," + c + " 不能构成三角形");
}
}
public static boolean isTriangle(int a, int b, int c) {
return (a + b > c) && (a + c > b) && (b + c > a);
}
}
```
在主方法中,我们使用`Scanner`类从命令行获取用户输入的三个整数。然后,我们调用`isTriangle`方法进行三角形判断。如果能构成三角形,`isTriangle`方法会返回`true`,我们打印输出"可以构成三角形";如果不能构成三角形,`isTriangle`方法会返回`false`,我们打印输出"a,b,c 不能构成三角形"。
用Java写判断三个整数是否能构成一个三角形,如果不能则抛出异常显示异常信息“边长:,,*不能构成三角形”。在主方法中输入的三个整数,并能捕获此异常。
可以使用以下的代码来实现:
```java
import java.util.Scanner;
public class Triangle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入三个整数:");
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
try {
if (a + b <= c || a + c <= b || b + c <= a) {
throw new Exception("边长:" + a + ", " + b + ", " + c + " 不能构成三角形");
} else {
System.out.println("边长:" + a + ", " + b + ", " + c + " 可以构成三角形");
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
```
首先,使用 `Scanner` 类来读取用户输入的三个整数。然后,使用 `try-catch` 语句块来捕获可能的异常。在 `try` 语句块中,使用条件语句判断三个整数的和是否大于第三个整数,如果不是,则抛出异常并显示异常信息;否则,打印成功信息。在 `catch` 语句块中,输出异常信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.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)