import java.util.InputMismatchException ; //数据类型错误
import java.lang.ArrayIndexOutOfBoundsException ; //越界
import java.util.Scanner ;public class boat
{
public int i2 = 2;
public int j2 = 2;
public void boat()
{
try
{
Scanner sc = new Scanner(System.in);
System.out.print("请输入战舰坐标(格式:(a b)):");
i2 = sc.nextInt();
j2 = sc.nextInt();
catch(InputMismatchException e)
{
System.out.println("数据错误!!!");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("数据超出范围!!!");
}
}
}
当发生异常时,如何使程序返回到try前边(也就是boat方法刚开始)???
import java.lang.ArrayIndexOutOfBoundsException ; //越界
import java.util.Scanner ;public class boat
{
public int i2 = 2;
public int j2 = 2;
public void boat()
{
try
{
Scanner sc = new Scanner(System.in);
System.out.print("请输入战舰坐标(格式:(a b)):");
i2 = sc.nextInt();
j2 = sc.nextInt();
catch(InputMismatchException e)
{
System.out.println("数据错误!!!");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("数据超出范围!!!");
}
}
}
当发生异常时,如何使程序返回到try前边(也就是boat方法刚开始)???
但是在InputMismatchException所在的catch块中可以实现,
在ArrayIndexOutOfBoundsException所在的catch块中就无法实现。
提示Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at sea.seaprint(sea.java:16)
at run.main(run.java:32)
这是怎么回事啊??
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at sea.seaprint(sea.java:16)
at run.main(run.java:32)这是那个run类:
public class run //定义运行类
{
public static void main(String args[])
{
submarine obj1 = new submarine();
boat obj2 = new boat(); System.out.println("显示海域:");
sea.seaprint(0,0,'S',2,2,'B');
while(true)
{
System.out.println("现在潜艇移动:"); obj1.submarine();
if(search.find(obj1.i1, obj1.j1,obj2.i2, obj2.j2)) {
System.out.println("潜艇发现战舰!!!");
sea.seaprint(obj1.i1, obj1.j1, 'S', obj1.i1, obj1.j1, 'S');
System.exit(1); }
sea.seaprint(obj1.i1, obj1.j1, 'S', obj2.i2, obj2.j2, 'B');
System.out.println("现在战舰移动:"); obj2.boat();
if(search.find(obj1.i1, obj1.j1,obj2.i2, obj2.j2)) {
System.out.println("战舰发现战舰!!!");
sea.seaprint(obj2.i2, obj2.j2, 'B', obj2.i2, obj2.j2, 'B'); System.exit(1); }
sea.seaprint(obj1.i1, obj1.j1, 'S', obj2.i2, obj2.j2, 'B'); }
}
}
麻烦帮我看看是怎么回事啊??我急求答案
try
{
Scanner sc = new Scanner(System.in);
System.out.print("请输入战舰坐标(格式:(a b)):");
i2 = sc.nextInt();
j2 = sc.nextInt();
break;
catch(InputMismatchException e)
{
System.out.println("数据错误!!!");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("数据超出范围!!!");
}}
不过,我就奇怪了。为啥要有这种设计逻辑呢?
很纠结。import java.util.InputMismatchException ; //数据类型错误
import java.lang.ArrayIndexOutOfBoundsException ; //越界
import java.util.Scanner ;public class boat
{
public int i2 = 2;
public int j2 = 2;
public void boat()
{
try
{
Scanner sc = new Scanner(System.in);
System.out.print("请输入战舰坐标(格式:(a b)):");
i2 = sc.nextInt();
j2 = sc.nextInt();
catch(InputMismatchException e)
{
System.out.println("数据错误!!!");
boat();
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("数据超出范围!!!");
boat();
}
}
}
{
try
{
正常代码(要返回的地方);
if (条件正确)
{
break;
}
}
catch (Exception e)
{
e.printStackTrace();
}
}