为了账号安全,请及时绑定邮箱和手机立即绑定

异常问题,求帮忙

public int selectServer(){

int choose=0;

try{

choose = input.nextInt();  

if(choose<1||choose>6)

throw new Exception();

return choose;

} catch (InputMismatchException e){

System.out.println("输入格式不正确,请重新正确数字:");

input.nextLine();

selectServer();

} catch (Exception e) {

System.out.println("请输入正确数字(1~6):");

input.nextLine();

selectServer();

}

return choose;

}

第一次输入错误抛出异常之后,重新输入正确的数但是返回值不正确

正在回答

5 回答

public static void selectServer(){
int choose=0;
input = new Scanner(System.in);
try{
choose = input.nextInt(); 
if(choose<1||choose>6){
throw new Exception();
}
System.out.println("final =" + choose);
} catch (InputMismatchException e){
System.out.println("输入格式不正确,请重新正确数字:");
input.nextLine();
selectServer();
} catch (Exception e) {
System.out.println("请输入正确数字(1~6):");
input.nextLine();
selectServer();
}

0 回复 有任何疑惑可以回复我~

具体参考线的代码

public static void selectServer(){
int choose=0;
input = new Scanner(System.in);
try{
choose = input.nextInt();  
if(choose<1||choose>6){
throw new Exception();
} 
System.out.println("final =" + choose);
} catch (InputMismatchException e){
System.out.println("输入格式不正确,请重新正确数字:");
input.nextLine();
selectServer();
} catch (Exception e) {
System.out.println("请输入正确数字(1~6):");
input.nextLine();
selectServer();
}

}


0 回复 有任何疑惑可以回复我~

因为你输入错误数据的时候,直接去selectServer(),没有 结束当前的线程,后面还有return choose,所有你第一次输入的数据会在第二次打印出来

0 回复 有任何疑惑可以回复我~
#1

王明晓 提问者

要怎么才能结束当前线程啊
2016-08-05 回复 有任何疑惑可以回复我~

这个函数,你每次出错之后,都输入一个数字,然后在重新执行selectServer(),又把choose置0 ,所以,,,,,你可以把那句话去掉试试

ps:新手,懂得不多。

0 回复 有任何疑惑可以回复我~
#1

王明晓 提问者

但是重新执行selectServer(),choose重置为0之后会继续让控制台输入一个choose给它赋值,应该会覆盖啊
2016-08-05 回复 有任何疑惑可以回复我~

666


0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
Java入门第二季 升级版
  • 参与学习       529871    人
  • 解答问题       6086    个

课程升级!以终为始告别枯燥,在开发和重构中体会Java面向对象编程的奥妙

进入课程

异常问题,求帮忙

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信