第一題
題目內容:
從鍵盤輸入一個整形數n,如果輸入正確的話,輸出10-n後的值,如果輸入錯誤的話輸出“not int”
最後輸出end
輸入輸出說明:
輸入:
asd
輸出:
not int
end
如果輸入的不是整數,則拋出異常類:InputMismatchException。
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner cin=new Scanner(System.in);
try {
int n=cin.nextInt();
System.out.println(10-n);
}
catch(InputMismatchException e) {
System.out.println("not int");
}
finally {
System.out.println("end");
}
}
}
第二題
題目內容:
寫一個方法void triangle(int a,int b,int c),判斷三個參數是否能構成一個三角形。如果不能則拋出異常IllegalArgumentException,顯示異常信息:“a,b,c不能構成三角形”;如果可以構成則顯示三角形三個邊長。在主方法中得到命令行輸入的三個整數,調用此方法,並捕獲異常。
輸入輸出說明:
2 4 3
三角形的三邊長爲:2,4,3
1 2 3
1,2,3不能構成三角形
1 2.0 3
請輸入整數作爲三角形的邊長!
輸入不匹配異常拋出InputMismatchException,非法數據異常拋出IllegalArgumentException。
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
class TestTriangle {
static void triangle(int a, int b,int c) throws IllegalArgumentException,InputMismatchException{
//starts
if(a<0||b<0||c<0||a+b<=c||a+c<=b||b+c<=a) throw new IllegalArgumentException();
System.out.printf("三角形的三邊長爲:%d,%d,%d\n",a,b,c);
//end
}
}
public class Main {
public static void main(String[] args) {
int a=0, b=0, c=0;
Scanner in = new Scanner(System.in);
try{
//starts
a = in.nextInt();
b = in.nextInt();
c = in.nextInt();
TestTriangle.triangle(a,b,c);
//end
}
catch(InputMismatchException e) {
System.err.println("請輸入整數作爲三角形的邊長!");
}
catch(IllegalArgumentException e) {
System.err.println("a,b,c不能構成三角形");
}
}
}
第三題
題目內容:
模擬向貨船上裝載集裝箱,每個集裝箱有一定重量,該重量(整數)大於100小於1000,貨船總重爲1000,裝載若干集裝箱後,如果貨船超重,那麼貨船認爲這是一個異常,將拒絕裝載集裝箱,但無論是否發生異常,貨船都需要正點啓航。
輸入:
199
400
300
300
輸出:
目前裝載了199噸貨物
目前裝載了599噸貨物
目前裝載了899噸貨物
超重
無法再裝載重量是300噸的集裝箱
貨船將正點啓航
自定義異常類DangerException,其中含有showError方法,在船類中有loading方法來拋出異常DangerException。
import java.util.Scanner;
class DangerException extends Exception {
//starts
public void showError() {
System.out.println("超重");
}
//end
}
class CargoBoat {
int realContent; //裝載的重量
int maxContent; //最大裝載量
public void setMaxContent(int c) {
maxContent = c;
}
public void loading(int m) throws DangerException {
//starts
realContent+=m;
if(realContent>maxContent)throw new DangerException();
System.out.printf("目前裝載了%d噸貨物\n",realContent);
//end
}
}
public class Main {
public static void main(String args[]) {
CargoBoat ship = new CargoBoat();
Scanner s=new Scanner(System.in);
ship.setMaxContent(1000);
int m=0;
try{
//starts
while(true) {
m=s.nextInt();
ship.loading(m);
}
//end
}
catch(DangerException e) {
//starts
e.showError();
System.out.printf("無法再裝載重量是%d噸的集裝箱\n",m);
//end
}
finally {
System.out.printf("貨船將正點啓航");
}
}
}