不明白,為什么輸入a值為整數值,也會報異常?求指教啊
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()方法執行了,結果為:"+result);
?? ??? ?
?? ?}
?? ?public int test(){
?? ??? ?Scanner input =new Scanner(System.in);
?? ??? ?try{
?? ??? ??? ?int b =100;
?? ??? ??? ?System.out.println("請輸入a的值");
?? ??? ??? ?int a =input.nextInt();
??????????? while(a >-1){
?????????? ??? ?b = a+b/a;
?????????? ??? ?a--; ??? ?
??????????? }
??????????? return b;
?? ??? ?}catch(Exception e){
?? ??? ??? ?e.printStackTrace();
?? ??? ??? ?System.out.println("異常報出,a應該為整數值");
?? ??? ??? ?return 0;
?? ??? ?}
?? ??? ?
?? ?}
}
2019-04-28
?while(a >-1){
?????????? ??? ?b = a+b/a;
?????????? ??? ?a--; ??? ?
??????????? }
這個循環,只要a>-1就循環,a--,那么不論你輸入啥,總會走到a=0的時候,0不能作為分母啊,會導致?b = a+b/a;
b無窮大,肯定報異常了啊,你可以把判斷條件改成 a>0