public static List<Integer> HailstoneSequence(int n) { if (n <= 0) { throw new IllegalArgumentException("Integer n must be > 0"); } List<Integer> sequence = new ArrayList<>(); sequence.add(n); while (n != 1) { if (n % 2 == 0) { n = n / 2; } else { n = 3 * n + 1; } sequence.add(n); } return sequence; }怎么改让程序能判断输入类型,比如输入的参数是浮点数的话会抛出异常
时间: 2024-02-14 14:16:40 浏览: 22
你可以使用Java中的Number类来判断输入参数的类型,如果输入参数是浮点数,则抛出异常。修改后的代码如下:
```
public static List<Integer> HailstoneSequence(Number n) {
if (n.doubleValue() <= 0) {
throw new IllegalArgumentException("Number n must be > 0");
}
if (n instanceof Double || n instanceof Float) {
throw new IllegalArgumentException("Number n must be an integer");
}
int num = n.intValue();
List<Integer> sequence = new ArrayList<>();
sequence.add(num);
while (num != 1) {
if (num % 2 == 0) {
num = num / 2;
} else {
num = 3 * num + 1;
}
sequence.add(num);
}
return sequence;
}
```
在方法中首先检查输入参数n是否小于等于0,如果是,则抛出异常。接着,使用instanceof运算符检查n是否为Double或Float类型,如果是,则抛出另一个异常。最后,将n转换为int类型,并在循环中使用它。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)