Java 如何捕获 NegativeArraySizeException?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24797013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to catch NegativeArraySizeException?
提问by Khyathi36
How to catch NegativeArraySizeException
in the given set of arrays.Here I want to display the largest number in given arrays ,but it is showing NegativeArraySizeException
.
如何捕捉NegativeArraySizeException
给定的数组集合。这里我想显示给定数组中的最大数字,但它正在显示NegativeArraySizeException
。
Example:
例子:
12, -23, 34
TreeSet ts=new TreeSet();
public void abc() {
Scanner sc=new Scanner(System.in);
int s1=0;
System.out.println("enter number of elemtns ");
s1=sc.nextInt();
int i[]=new int[s1];
for(int i2=0; i2<=i.length; i2++) {
int s2=sc.nextInt();
if(s2<0)
throw new NegativeArraySizeException();
int i1[]=new int[s2];
System.out.println("first,,,,"+s2);
ts.add(s2);
System.out.println("higest....."+ts.last());
}
}
public static void main(String[] args) {
StringAbc s=new StringAbc(); s.abc();
}
回答by SparkOn
What I understand is you want to implement this
我的理解是你想实现这个
public void abc() {
Scanner sc=new Scanner(System.in);
int s1=0;
System.out.println("enter number of elemtns ");
//Read the size of array from user and check if it is not negative
s1=sc.nextInt();
if(s1<0) throw new NegativeArraySizeException("Array size cannot be negative.");
int i[]=new int[s1];
int s2 = 0;
for(int i2=0;i2<i.length;i2++) {
System.out.println("Enter element");
s2=sc.nextInt();
//get input from user and dont allow negtive numbers in the array
if(s2<0) throw new IllegalArgumentException("Negative numbers not allowed");
ts.add(s2);
}
System.out.println("first,,,,"+s2);
System.out.println("higest....."+ts.last());
}
回答by kajacx
Something like this?
像这样的东西?
int arrSize = -8;
try {
int[] myArray = new int[arrSize];
} catch (NegativeArraySizeException ex) {
System.out.println("Can't create array of negative size");
}
Output: Can't create array of negative size
输出: Can't create array of negative size
回答by vinayknl
Surround below code in try-catch block
环绕在 try-catch 块中的代码下方
StringAbc s=new StringAbc(); s.abc();
like
喜欢
try
{
StringAbc s=new StringAbc(); s.abc();
}
catch (NegativeArraySizeException ex)
{
System.out.println( ex.getMessage());
}