for循環和try.catch語句的搭配使用在輸入值時為什么會有問題
for?(;;){
try{
int?a=input.nextInt();
int?b=input.nextInt();
try{
if?(a/b>2){
System.out.println("Done!");
break;
}else{
System.out.println("please?input?again");
}
}
catch(Exception?e){
System.out.println("if?is?wrong");
}
}
catch(Exception?e){
System.out.println("input?is?wrong");
continue;//加不加不影響
}
}這段代碼在執行時,如果輸入1和2,則會繼續執行;輸入2和0,會報錯并繼續要求輸入;但是如果輸了1.5之類的違規數字,則會直接無限循環報錯"input?is?wrong"而不是繼續要求執行輸入。用debug檢查發現每次執行到輸入就自動跳到最后了。請問為什么?
2015-06-29
自己已經解決,需要將Scanner input=new Scanner(System.in);放到try里面才行,不然input已經是定值了