在一个java类中 要求用户选择整形1 或2或3或4 这个四个数字,
可是如果当用户选择了别的字符型如 用户输入a,b什么的就是出现异常,
我用了try catch 捕获了异常 。
可是我希望在用户输入错误的时候提示输入错误,并且重新输入选择(要求一定用try catch 来写!)
我应该怎么改我的代码呢?
do{
System.out.print("玩家1选择角色");
try {
sr1 = scanner.nextInt();
setRole(1,sr1);
} catch (Exception e) {
// e.printStackTrace();
System.out.println("角色选择必须输入数字1,2,3,4");
if(sr1==1||sr1==2||sr1==3||sr1==4){
f = false;
}
}
}while(f==true);
可是如果当用户选择了别的字符型如 用户输入a,b什么的就是出现异常,
我用了try catch 捕获了异常 。
可是我希望在用户输入错误的时候提示输入错误,并且重新输入选择(要求一定用try catch 来写!)
我应该怎么改我的代码呢?
do{
System.out.print("玩家1选择角色");
try {
sr1 = scanner.nextInt();
setRole(1,sr1);
} catch (Exception e) {
// e.printStackTrace();
System.out.println("角色选择必须输入数字1,2,3,4");
if(sr1==1||sr1==2||sr1==3||sr1==4){
f = false;
}
}
}while(f==true);
do{
try{
//正常的流程
break;
}catch (Exception e) {
//异常的流程
continue;
}
}while(true);但java设计的一个原则是catch不应被用来控制程序逻辑,只应该用于异常处理
System.out.print("玩家1选择角色");
try {
sr1 = scanner.nextInt();
setRole(1,sr1);
} catch (Exception e) {
// e.printStackTrace();
System.out.println("角色选择必须输入数字1,2,3,4");
}
if(sr1==1||sr1==2||sr1==3||sr1==4){
f = false; }
}while(f==true);
int a;
do {
try {
System.out.println("请选择角色....");
Scanner scanner = new Scanner(System.in);
a = Integer.parseInt(scanner.nextLine());
System.out.println("a == "+a);
if(a != 1 && a != 2 && a !=3 && a != 4){
throw new Exception("只能输入1、2、3、4");
}else{
break;
}
} catch (Exception e) {
// e.printStackTrace();
System.out.println("角色选择必须输入数字1,2,3,4");
}
} while (true);
}
public static void main(String[] args) {
int a;
do {
try {
System.out.println("请选择角色....");
Scanner scanner = new Scanner(System.in);
a = Integer.parseInt(scanner.nextLine());
System.out.println("a == "+a);
if(a != 1 && a != 2 && a !=3 && a != 4){
throw new Exception("只能输入1、2、3、4");
}
} catch (Exception e) {
// e.printStackTrace();
System.out.println("角色选择必须输入数字1,2,3,4");
}
} while (true);
}
lz 说的 循环不结束 是这种情况么
不 continue;也可以的吧。
try{
//正常的流程
break;
}catch (Exception e) {
//异常的流程
continue;
}
}while(true);
try{
//正常的流程
break;
}catch (Exception e) {
//异常的流程
continue;
}
}while(true);
try{
if(no exception){
System.out.println("success");
break;
}
} catch (Exception ex){
System.out.println("please input (1-4)";
}
}
label:
while(true){
System.out.println("Enter a number ");
Scanner in = new Scanner(System.in);
int s = in.nextInt();
if(s<10)break label;
System.out.println("number is"+s);
}
用标签。和C#中的goto一样
如果跳出后还想运行while(true)
可以用continue label;