• Java异常课后习题编程题


    教材Java面向对象程序设计(第二版) 袁绍欣 第七章6、7

    6. 编写一个程序方法,对空指针异常、除数为零异常给出出错的中文提示。当有新异常发生时,可扩展该方法中的代码进行统一处理。

    public class Test{
    	public static void main(String[] args) {
            try {
            	String s = null;
                //System.out.println(1/0);//除零异常
                System.out.println(s.charAt(0));//空指针异常
            }catch (NullPointerException e) {
                System.out.println("空指针异常");
            }catch (ArithmeticException e) {
                System.out.println("计算异常");
            }catch (Exception e) {
                System.out.println("其他异常");
                e.printStackTrace();
            }
        }
    

    7. 从屏幕输入10个数,在输入错误的情况下,给出相应的提示,并继续输入。在输入完成的情况下,找到最大最小数。

    import java.util.Scanner;
    public class Test {
        private static Scanner sc;
    
    	public static void main(String[] args) {
              int index = 0;
              int[] array = new int[10];
              int max,min;
              while (true) {
                    if (index == array.length) { break;}
                    sc = new Scanner(System.in);
                    System.out.print("输入" + (index + 1) + ":");
                    try {
                         array[index] = sc.nextInt();
                         index++;
                     } 
                     catch (Exception e) {System.out.println("输入错误,重新输入!");}
               }
               max = array[0];
               min = array[0];
               for (int i = 1; i < array.length; i++) {
                     if (array[i] > max) {max = array[i];}
                     if (array[i] < min) {min = array[i];}
                }
               System.out.println("max = " + max);
               System.out.println("min = " + min);
              
         }
    

    运行结果:

    输入1:1
    输入2:5
    输入3:999
    输入4:q
    输入错误,重新输入!
    输入4:aaa
    输入错误,重新输入!
    输入4:66
    输入5:-4
    输入6:-2222
    输入7:2c
    输入错误,重新输入!
    输入7:0
    输入8:63
    输入9:1
    输入10:+6
    max = 999
    min = -2222
    
  • 相关阅读:
    集合
    字典
    Visual Studio 2017 发布
    表现设身处地的方法:杜彬(Ben Duffy)方法
    Can RemObjects SDK parameters be passed via the URI?
    转:RemObjects SDK 简介
    转:RemObject 服务器端自调用的方法
    转: Delphi多层开发方案比较
    Embed
    log4d 的使用(转)
  • 原文地址:https://www.cnblogs.com/myzhibei/p/12890551.html
Copyright © 2020-2023  润新知