不明白,為什么輸入a值為整數(shù)值,也會(huì)報(bào)異常?求指教啊
package test.Exception;
/*異常拋出及處理:try? catch? finally
?*
?*/
import java.util.*;
public class Exception_Test1 {
?? ?public static void main(String[] args) {
?? ??? ?// TODO Auto-generated method stub
?? ??? ?Exception_Test1 Test =new Exception_Test1();
?? ??? ?int result =Test.test();
?? ??? ?System.out.println("test()方法執(zhí)行了,結(jié)果為:"+result);
?? ??? ?
?? ?}
?? ?public int test(){
?? ??? ?Scanner input =new Scanner(System.in);
?? ??? ?try{
?? ??? ??? ?int b =100;
?? ??? ??? ?System.out.println("請(qǐng)輸入a的值");
?? ??? ??? ?int a =input.nextInt();
??????????? while(a >-1){
?????????? ??? ?b = a+b/a;
?????????? ??? ?a--; ??? ?
??????????? }
??????????? return b;
?? ??? ?}catch(Exception e){
?? ??? ??? ?e.printStackTrace();
?? ??? ??? ?System.out.println("異常報(bào)出,a應(yīng)該為整數(shù)值");
?? ??? ??? ?return 0;
?? ??? ?}
?? ??? ?
?? ?}
}
2019-04-28
?while(a >-1){
?????????? ??? ?b = a+b/a;
?????????? ??? ?a--; ??? ?
??????????? }
這個(gè)循環(huán),只要a>-1就循環(huán),a--,那么不論你輸入啥,總會(huì)走到a=0的時(shí)候,0不能作為分母啊,會(huì)導(dǎo)致?b = a+b/a;
b無窮大,肯定報(bào)異常了啊,你可以把判斷條件改成 a>0