for循環(huán)和try.catch語(yǔ)句的搭配使用在輸入值時(shí)為什么會(huì)有問(wèn)題
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;//加不加不影響 } }
這段代碼在執(zhí)行時(shí),如果輸入1和2,則會(huì)繼續(xù)執(zhí)行;輸入2和0,會(huì)報(bào)錯(cuò)并繼續(xù)要求輸入;但是如果輸了1.5之類的違規(guī)數(shù)字,則會(huì)直接無(wú)限循環(huán)報(bào)錯(cuò)"input?is?wrong"而不是繼續(xù)要求執(zhí)行輸入。用debug檢查發(fā)現(xiàn)每次執(zhí)行到輸入就自動(dòng)跳到最后了。請(qǐng)問(wèn)為什么?
2015-06-29
自己已經(jīng)解決,需要將Scanner input=new Scanner(System.in);放到try里面才行,不然input已經(jīng)是定值了