How to resolve the Java NegativeArraySizeException exception?
The NegativeArraySizeException in Java indicates that an array is being created with a negative size. To fix this exception, ensure that no negative sized arrays are specified in your code.
Here are some ways to resolve the NegativeArraySizeException exception:
- Check the calculation logic of the array size to ensure that negative sizes do not occur.
- Add conditional statement to prevent the creation of arrays with negative size.
- You can use a try-catch block to catch the NegativeArraySizeException and handle it by informing the user to input a valid array size when the exception is caught.
- Use the Math.abs() method to get the absolute value and avoid negative numbers.
Here is a sample code demonstrating how to handle the NegativeArraySizeException.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("请输入数组大小:");
int size = scanner.nextInt();
if (size < 0) {
throw new NegativeArraySizeException("数组大小不能为负数");
}
int[] array = new int[size];
System.out.println("数组创建成功,大小为:" + size);
} catch (NegativeArraySizeException e) {
System.out.println("输入的数组大小为负数,请重新输入");
}
}
}
In the example above, we use a try-catch block to catch the NegativeArraySizeException and prompt the user to input a valid array size when the exception is caught. This helps prevent the program from throwing an exception due to a negative array size. You can choose an appropriate solution to handle the NegativeArraySizeException based on your specific situation.