練習1
寫一個方法void triangle(int a,int b,int c),判斷三個參數是否能構成一個三角形。如果不能則拋出異常illegalargumentexception,顯示異常信息:a,b,c “不能構成三角形”;如果可以構成則顯示三角形三個邊長。在主方法中得到命令行輸入的三個整數,調用此方法,并捕獲異常。
兩邊之和大于第三邊:a+b>c
兩邊之差小于第三邊:c-a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
package 異常; import java.util.arrays; import java.util.inputmismatchexception; import java.util.scanner; public class testtriangle { public static void triangle( int a, int b, int c) throws illegalargumentexception, inputmismatchexception{ int x[] = new int [ 3 ]; x[ 0 ] = a; x[ 1 ] = b; x[ 2 ] = c; arrays.sort(x); if ((x[ 0 ]+x[ 1 ]>x[ 2 ])&&(x[ 2 ]-x[ 1 ]<x[ 0 ])) system.out.println( "三角形的三邊長為:" +a+ "," +b+ "," +c); else throw new illegalargumentexception(); } public static void main(string[] args) { int a= 0 , b= 0 , c= 0 ; scanner in = new scanner(system.in); system.out.println( "請分別輸入三角形的三邊長:" ); try { a = in.nextint(); b = in.nextint(); c = in.nextint(); triangle(a, b, c); } catch (inputmismatchexception e1){ system.err.println( "請輸入整數作為三角形的邊長!" ); e1.printstacktrace(); } catch (illegalargumentexception e2){ system.err.println(a+ "," +b+ "," +c+ "不能構成三角形" ); } } } |
練習2:
從命令行輸入5個整數,放入一整型數組,然后打印輸出。要求:
如果輸入數據不為整數,要捕獲輸入不匹配異常,顯示“請輸入整數”;如果輸入數據多余5個,捕獲數組越界異常,顯示“請輸入5個整數”。
無論是否發生異常,都輸出“感謝使用本程序!”
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
package 異常; import java.util.inputmismatchexception; import java.util.scanner; public class testarray { public static void main(string[] args) { int a[] = new int [ 5 ]; system.out.println( "請輸入5個數:" ); system.out.println( "最后輸入一個非數字結束輸入操作。" ); scanner in = new scanner(system.in); try { int i = 0 ; while (in.hasnextdouble()){ a[i] = in.nextint(); i++; } if (i< 5 ) throw new arrayindexoutofboundsexception(); for ( int j= 0 ;j< 5 ;j++) system.out.print(a[j]+ " " ); system.out.println(); } catch (inputmismatchexception e1){ system.err.println( "請輸入整數作為數組元素!" ); e1.printstacktrace(); } catch (arrayindexoutofboundsexception e2){ system.err.println( "請輸入5個數!" ); e2.printstacktrace(); } finally { system.out.print( "感謝使用本程序!" ); } } } |
總結
以上就是本文關于java編程異常簡單代碼示例的全部內容,希望對大家有所幫助。有什么問題可以隨時留言,小編會及時回復大家的。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/evan19870504/article/details/78469784