我自定义了一个异常,就是在输入负数的情况下捕获异常,并从对话框输出 "输入错误!请输入一个大于零的数!",可我输入负数当然时候,不仅在对话框输出了这个异常信息,控制台也显示“Exception in thread "main" java.lang.NegativeArraySizeException
at Shiyan.main(Shiyan.java:16)”,它提示的是数组大小不能为负。我已经捕获了这个异常,为什么控制太还输出异常信息?怎样让异常信息只在对话框输出?import javax.swing.JOptionPane;
public class Shiyan extends Exception{
void test(int x)throws Shiyan{
if(x<=0)throw new Shiyan();
}
public static void main(String[] args) {
Shiyan T=new Shiyan();
int t=0;
String s=JOptionPane.showInputDialog("请输入一个数:");
try{
t=Integer.parseInt(s);
T.test(t);
}catch(Shiyan e){
JOptionPane.showMessageDialog(null,"输入错误!请输入一个大于零的数!");
}
int array[][]=new int[t][7];
for(int i=0;i<t;i++){
for(int h=0;h<7;h++){
int randr=1+(int)(Math.random()*30);
boolean f=true;
for(int k=0;k<i;k++){
if(randr==array[k][h]){
f=false;break;
}
}
if(f) array[i][h]=randr;
else i--;
}
}
for(int i=0;i<t;i++){
for(int q:array[i]) System.out.print(q+" ");
System.out.println();
} }
}
at Shiyan.main(Shiyan.java:16)”,它提示的是数组大小不能为负。我已经捕获了这个异常,为什么控制太还输出异常信息?怎样让异常信息只在对话框输出?import javax.swing.JOptionPane;
public class Shiyan extends Exception{
void test(int x)throws Shiyan{
if(x<=0)throw new Shiyan();
}
public static void main(String[] args) {
Shiyan T=new Shiyan();
int t=0;
String s=JOptionPane.showInputDialog("请输入一个数:");
try{
t=Integer.parseInt(s);
T.test(t);
}catch(Shiyan e){
JOptionPane.showMessageDialog(null,"输入错误!请输入一个大于零的数!");
}
int array[][]=new int[t][7];
for(int i=0;i<t;i++){
for(int h=0;h<7;h++){
int randr=1+(int)(Math.random()*30);
boolean f=true;
for(int k=0;k<i;k++){
if(randr==array[k][h]){
f=false;break;
}
}
if(f) array[i][h]=randr;
else i--;
}
}
for(int i=0;i<t;i++){
for(int q:array[i]) System.out.print(q+" ");
System.out.println();
} }
}
}catch(Shiyan e){
JOptionPane.showMessageDialog(null,"输入错误!请输入一个大于零的数!");
}
为:
}catch(Shiyan e){
JOptionPane.showMessageDialog(null,"输入错误!请输入一个大于零的数!");
return; //结束该方法
}
int array[][]=new int[t][7];
这里,t作为负数怎么能作为数组的大小??
这里你必须用一个循环,当catch了exception之后,重新去输入
boolean num=false;
while(!num)
{
String s=JOptionPane.showInputDialog("请输入一个数:");
try
{
t=Integer.parseInt(s);
T.test(t);
num=true;
}catch(Shiyan e){
JOptionPane.showMessageDialog(null,"输入错误!请输入一个大于零的数!");
}
}
String s;
do{
s=JOptionPane.showInputDialog("请输入一个数:");
try{
t=Integer.parseInt(s);
T.test(t);
}catch(Shiyan e){
JOptionPane.showMessageDialog(null,"输入错误!请输入一个大于零的数!");
}
}while(t<=0);
String s;
do{
s=JOptionPane.showInputDialog("请输入一个数:");
try{
t=Integer.parseInt(s);
T.test(t);
}catch(Shiyan e){
JOptionPane.showMessageDialog(null,"输入错误!请输入一个大于零的数!");
}
}while(t<=0);排个版