第六次实训作业

第一题:

编写一个类ExceptionTest,在main方法中使用try-catch-finally语句结构实现:

try语句块中,编写两个数相除操作,相除的两个操作数要求程序运行时用户输入;
在catch语句块中,捕获被0除所产生的异常,并输出异常信息;
在finally语句块中,输出一条语句

package shixun6;
import java.util.Scanner;
public class ExceptionTest extends Exception{
private static final int Scanner = 0;
private static Scanner sc;
public void ExceptionText(){
System.out.println("分母不能为0");
}

public static void main(String[] args) {
int a,b,c;
System.out.println("输入两个数:\n");
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
b=sc.nextInt();

try{
c=a/b;

}
catch(ArithmeticException e){
System.out.println("分母不能为0");
}

}
private static int Scanner(int i, int j) {
// TODO Auto-generated method stub
return 0;
}
}

运行结果:

 
 
第二题:编写一个应用程序,要求从键盘输入一个double型的圆的半径,计算并输出其面积。测试当输入的数据不是double型数据(如字符串“abc”)会产生什么结果,怎样处理。
package yichangchuli;
import java.util.InputMismatchException;
import java.util.Scanner;
public class yuan {
   
 public static void main(String[] args) {
   Scanner sc=new Scanner(System.in);
  double a;
  System.out.println("输入1个半径:\n");
  try{
   a=sc.nextDouble();
  }catch(InputMismatchException e){
  System.out.println("输入类型不匹配");
 }
}}

  运行结果:
 
第三题:为类的属性“身份证号码 .id”设置值,当给的的值长度为18时,赋值给id,当值长度不是18时,抛出IllegalArgumentException异常,然后捕获和处理异常,编写程序实现以上功能。

package shixun6;
import java.util.*;
public class sfz {
static void pop(int l)throws IllegalArgumentException{
if(l<18||l>18) {
throw new IllegalArgumentException("不是18位数");
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner rd=new Scanner(System.in);
String id;
int n;
id=rd.next();
n=id.length();
try {
pop(n);
System.out.println("身份证:"+id);

}catch(IllegalArgumentException e){
System.out.println(e);
}
}

}

猜你喜欢

转载自www.cnblogs.com/lemon0718/p/10830812.html