Java from entry to master chapter exercises - Chapter 9

Java from entry to master chapter exercises - Chapter 9

Exercise 1

Comprehensive exercise 1: Raise an out-of-bounds exception Write a simple program to generate an out-of-bounds exception (IndexOutOfBoundsException).

package org.hj.chapter9;

import java.util.ArrayList;

public class IndexOutOfBoundsException {
    
    

    /**
     * 综合练习1:引发越界异常 编写一个简单的程序,使之产生越界异常(IndexOutOfBounds Exception)。
     */

    public static void main(String[] args) {
    
    
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        //直接引用不存在的元素时产生
        System.out.println(list.get(3));
    }
}

Exercise 2

Comprehensive Exercise 2: Data Type Conversion Exception Write a simple program to generate a data type conversion exception (NumberFormatException).

package org.hj.chapter9;

public class NumberFormatException {
    
    

    /**
     * 综合练习2:数据类型转换异常 编写一个简单程序,使之产生数据类型转换异常(NumberFormatException)。
     */

    public static void main(String[] args) {
    
    

        String a = "123 ";//有空格
        String b = "123.123";//小数
        String c = "123*";//带符号
        System.out.println(Integer.parseInt(a));
        System.out.println(Integer.parseInt(b));
        System.out.println(Integer.parseInt(c));

    }
}

Exercise 3

Comprehensive exercise 3: An exception occurred in an array Briefly describe the traversal process of an integer array (such as "int a[] = { 1, 2, 3, 4 };") on the console; and show that when the value of i is How often does an exception occur, and what type of exception is it?

package org.hj.chapter9;

public class ArrayException {
    
    

    /**
     * 综合练习3:数组发生的异常 在控制台上简述一个整型数组(如"int a[] = { 1, 2, 3, 4 };")遍历的过程;
     * 并体现出当i的值为多少时,会产生异常,异常的种类是什么?
     */

    public static void main(String[] args) {
    
    
        int arr[] = {
    
    1,2,3,4,5};
        int i = 0;
        try {
    
    
            for (i = 0; i >= 0; i++) {
    
    
                System.out.println(arr[i]);
            }
        } catch (Exception e) {
    
    
            System.out.println("遍历数组发生异常" + "i = " + i);
            e.printStackTrace();
        }
    }
}

Exercise 4

Comprehensive exercise 4: Exceptions caused by multiplication Create a Number class, and use the method count() in the class to get the result of multiplying two integers whose data type is int, and use the try-catch statement in the main method that calls this method Catch 12315 times 57876876 possible exceptions.

package org.hj.chapter9;

public class MultiplicationException {
    
    

    /**
     * 综合练习4:乘法引发的异常 创建Number类,通过类中的方法count()可得到两个数据类型为int型的整数相乘后的结果,
     * 在调用该方法的主方法中使用try-catch语句捕捉12315乘以57876876可能发生的异常。
     */

    public static void main(String[] args) {
    
    
        Number number = new Number();
        try {
    
    
            int count = number.count(12315, 57876876);
            System.out.println("计算结果为" + count);
        } catch (Exception e) {
    
    
            System.out.println("计算异常,发生溢出");
        }

    }
}

class Number {
    
    

    public int count(int a, int b) throws Exception{
    
    
        int result = a * b;
        if (result < 0) {
    
    
            throw new Exception("乘法溢出,请使用更大的单位");
        }
        return result;
    }
}

Exercise 5

Comprehensive exercise 5: The divisor cannot be 0 Use static variables, static methods and the throws keyword to realize that when two numbers are divided and the divisor is 0, the program will catch and process the thrown ArithmeticException (arithmetic exception).

package org.hj.chapter9;

public class ArithmeticException {
    
    

    /**
     * 综合练习5:除数不能为0 使用静态变量、静态方法以及throws关键字,实现当两个数相除且除数为0时,
     * 程序会捕获并处理抛出的ArithmeticException异常(算术异常),运行结果如图9.9所示。
     */

    public static void main(String[] args) {
    
    
        try {
    
    
            int a = 1/0;
        } catch (Exception e) {
    
    
            throw new RuntimeException(e);
        }
    }
}

Exercise 6

Comprehensive Exercise 6: Verify the age format Write an information entry program to obtain the name and age entered by the user. If the age entered by the user is not the correct age number (such as 0.5), an exception is thrown and the user is asked to re-enter; if the age is correct, the information entered by the user is printed.

package org.hj.chapter9;

import java.util.Scanner;

public class VerifyAgeFormat {
    
    

    /**
     * 综合练习6:校验年龄格式 编写一个信息录入程序,获取用户输入的姓名和年龄。
     * 如果用户输入的年龄不是正确的年龄数字(如0.5),则抛出异常并让用户重新输入;
     * 如果年龄正确,则打印用户输入的信息。
     */

    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        String name = null;
        int age = 0;
        while (true) {
    
    
            System.out.print("请输入姓名:");
            name = scanner.nextLine();
            try {
    
    
                System.out.print("请输入年龄:");
                //将输入的数据转换成int类型,转换成功则格式正确,失败则抛出一场
                age = Integer.parseInt(scanner.nextLine());
                if (age < 0 || age > 200) {
    
    
                    throw new RuntimeException("年龄不合法,请重新输入");
                }
                break;
            } catch (Exception e) {
    
    
                //
                System.out.println("年龄格式不正确,请重新输入");
            }
        }
        System.out.println("姓名:" + name + ",年龄:" + age);
    }
}

Exercise 7

Comprehensive Exercise 7: Breaking the Loop Write code that uses a for loop to output 0 to 9 on the console. The code needs to implement the following two functions: when the value of the loop variable is 2, an exception is thrown and the loop is interrupted; when the value of the loop variable is 2, although an exception is thrown, the loop will not be interrupted.

package org.hj.chapter9;

public class BreakLoop {
    
    

    /**
     * 综合练习7:中断循环 编写使用for循环在控制台上输出0~9的代码。
     * 代码要实现以下两个功能:当循环变量的值为2时,抛出异常,循环中断;
     * 当循环变量的值为2时,虽然会抛出异常,但是循环不会中断。
     */

    public static void main(String[] args) throws Exception{
    
    

        for (int i = 0; i < 10; i++) {
    
    
            if (i == 2) {
    
    
                throw new Exception("循环变量的值为2时,抛出异常,循环中断");
            }
            System.out.println(i);
        }

//        for (int i = 0; i < 10; i++) {
    
    
//            try {
    
    
//                if (i == 2) {
    
    
//                    System.out.println("i值等于" + i);
//                }
//            } catch (Exception e) {
    
    
//                throw new RuntimeException("抛出一场:i值等于" + i);
//            }
//            System.out.println(i);
//        }
    }
}

Exercise 8

Comprehensive exercise 8: Calculate the greatest common divisor Create a Computer class, which has a method to calculate the greatest common divisor of two numbers. If a negative integer is passed to this method, the method will throw a custom exception.

package org.hj.chapter9;

public class CommonDivisor {
    
    

    /**
     * 综合练习8:计算最大公约数 创建Computer类,该类中有一个计算两个数的最大公约数的方法,
     * 如果向该方法传递负整数,该方法就会抛出自定义异常。
     */

    public static void main(String[] args) {
    
    

        int i = new Computer().calculateCommonDivisor(9, 100);
        System.out.println(i);
    }
}

class Computer {
    
    

    public int calculateCommonDivisor(int a, int b) {
    
    
        if (b == 0) {
    
    
            return a;
        }
        //递归调用该方法
        return calculateCommonDivisor(b, a % b);
    }
}

Guess you like

Origin blog.csdn.net/dedede001/article/details/130290457