2019年2月18日,异常作业
java源代码分享地址为:
链接:https://pan.baidu.com/s/1y_sSFfg9fszIGPatlcnn9w
提取码:0ih8
复制这段内容后打开百度网盘手机App,操作更方便哦
作业1:
编辑代码如下:
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("欢迎提出建议!");
}
}
}
输出结果为:
请输入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
欢迎提出建议!
作业2
创建人类:
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());
}
}
编写测试类:
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