java源代碼分享地址爲:java
連接:https://pan.baidu.com/s/1y_sSFfg9fszIGPatlcnn9w
提取碼:0ih8
複製這段內容後打開百度網盤手機App,操做更方便哦測試
做業1:this
編輯代碼以下:spa
import java.util.InputMismatchException; import java.util.Scanner; public class LianXi { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("請輸入1~3中的任意數字,將會顯示相應的課程內容:"); int num = 0; try { num = input.nextInt(); switch (num){ case 1: System.out.println("數學課!"); break; case 2: System.out.println("語文課!"); break; case 3: System.out.println("英語課!"); break; default: System.out.println("輸入的數字有誤!"); break; } }catch (InputMismatchException e){ System.err.println("輸入錯誤!"); e.printStackTrace(); System.out.println(e.getMessage()); }catch (Exception e){ System.err.println("輸入錯誤!"); }finally{ System.out.println("歡迎提出建議!"); } } }
輸出結果爲:code
請輸入1~3中的任意數字,將會顯示相應的課程內容: b 輸入錯誤! java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextInt(Scanner.java:2117) at java.util.Scanner.nextInt(Scanner.java:2076) at LianXi.main(LianXi.java:12) null 歡迎提出建議!
做業2blog
建立人類:get
package com.yichang.zuoye; public class Person { private String name; private String sex; private int age; public Person() { } public Person(String name, String sex, int age) { this.name = name; this.sex = sex; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex)throws Exception { if(sex.equals("男")||sex.equals("女")){ this.sex = sex; }else{ throw new Exception("性別只能夠是男或者女!"); } } public int getAge() { return age; } public void setAge(int age) throws Exception { if(age>=1&&age<=100){ this.age = age; }else{ throw new Exception("年齡必須在1到100之間!"); } } public void showInfo(){ System.out.println("本人叫"+this.getName()+",性別:"+this.getSex()+",年齡爲:"+this.getAge()); } }
編寫測試類:input
package com.yichang.zuoye; public class TestPerson { public static void main(String[] args) { Person p = new Person(); try{ p.setAge(101); }catch (Exception e){ e.printStackTrace(); } } }
輸出結果爲:數學
java.lang.Exception: 年齡必須在1到100之間! at com.yichang.zuoye.Person.setAge(Person.java:46) at com.yichang.zuoye.TestPerson.main(TestPerson.java:7) Process finished with exit code 0