请编写一个Java程序,要求输入一个整数n,然后输出n个随机字母,如果n不在1到10之间,则抛出一个自定义的异常InvalidInputException,并在主函数中进行捕获和处理。
时间: 2024-03-24 10:37:10 浏览: 9
好的,下面是代码实现:
```java
import java.util.Random;
// 自定义异常类
class InvalidInputException extends Exception {
public InvalidInputException(String message) {
super(message);
}
}
public class RandomLetters {
public static void main(String[] args) {
try {
int n = Integer.parseInt(args[0]);
if (n < 1 || n > 10) {
throw new InvalidInputException("n必须在1到10之间");
}
String letters = generateRandomLetters(n);
System.out.println(letters);
} catch (InvalidInputException e) {
System.err.println("发生异常:" + e.getMessage());
} catch (NumberFormatException e) {
System.err.println("输入的n不是一个整数");
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("请在命令行输入一个整数n");
}
}
// 生成n个随机字母
private static String generateRandomLetters(int n) {
Random rand = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
char c = (char) ('a' + rand.nextInt(26));
sb.append(c);
}
return sb.toString();
}
}
```
在主函数中,我们首先尝试将命令行参数转换为一个整数n。如果转换失败,我们捕获NumberFormatException异常并输出错误信息。如果n不在1到10之间,我们手动抛出一个InvalidInputException异常。在调用generateRandomLetters函数时,我们可以放心地传入n参数,因为我们已经保证了n的有效性。如果generateRandomLetters函数中发生异常,它将自动抛出并在主函数中被捕获和处理。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)