【NumberFormatException异常】编写一个程序,提示用户输入两个整数,然后显示它们的和。用户输入错误时提示用户重新输入。 【ArrayIndexOutOfBoundsException异常】编写一个程序,创建一个由100个随机选取的整数构成的数组;提示用户输入数组下标,然后显示元素的值,如果指定的下标越界,显示消息out of bounds。 【OutOfMemoryError错误】编写一个程序,它能导致JVM抛出一个OutOfMemoryError,然后捕获并处理这个错误。
时间: 2024-02-09 20:10:39 浏览: 22
好的,我会一一回答你的问题。
1. 编写程序求两个整数的和,用户输入错误时提示重新输入:
```java
import java.util.Scanner;
public class SumOfTwoNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isInputValid = false;
while (!isInputValid) {
try {
System.out.print("请输入第一个整数:");
num1 = Integer.parseInt(input.nextLine());
System.out.print("请输入第二个整数:");
num2 = Integer.parseInt(input.nextLine());
isInputValid = true;
} catch (NumberFormatException e) {
System.out.println("您输入的不是整数,请重新输入。");
}
}
int sum = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + sum);
}
}
```
2. 编写程序创建一个由100个随机选取的整数构成的数组,提示用户输入数组下标,然后显示元素的值,如果指定的下标越界,显示消息out of bounds。
```java
import java.util.Random;
import java.util.Scanner;
public class ArrayIndexOutOfBounds {
public static void main(String[] args) {
Random rand = new Random();
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(1000);
}
Scanner input = new Scanner(System.in);
boolean isInputValid = false;
while (!isInputValid) {
try {
System.out.print("请输入数组下标(0 ~ 99):");
int index = Integer.parseInt(input.nextLine());
System.out.println("arr[" + index + "] = " + arr[index]);
isInputValid = true;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组下标越界,请重新输入。");
} catch (NumberFormatException e) {
System.out.println("您输入的不是整数,请重新输入。");
}
}
}
}
```
3. 编写程序导致JVM抛出一个OutOfMemoryError,然后捕获并处理这个错误。
```java
public class OutOfMemoryErrorExample {
public static void main(String[] args) {
int[] arr = new int[Integer.MAX_VALUE];
System.out.println("程序结束。");
}
}
```
这个程序会尝试创建一个长度为Integer.MAX_VALUE的整型数组,这个数组的长度超出了Java虚拟机的内存限制,会导致JVM抛出一个OutOfMemoryError。我们可以使用try-catch语句来捕获这个错误并进行处理:
```java
public class OutOfMemoryErrorExample {
public static void main(String[] args) {
try {
int[] arr = new int[Integer.MAX_VALUE];
} catch (OutOfMemoryError e) {
System.out.println("抛出了OutOfMemoryError错误。");
}
System.out.println("程序结束。");
}
}
```
这个程序中,我们在try块中尝试创建一个超大数组,如果抛出了OutOfMemoryError错误,就会跳转到catch块中,输出一条错误信息。无论有没有抛出错误,程序都会继续执行,输出一条结束信息。