java 语言程序设计 第十二章(12.1、12.2、12.3、12.4、12.5、12.6)

来源:互联网 发布:网络计划图绘制软件 编辑:程序博客网 时间:2024/05/21 05:21

程序小白,希望和大家多交流,共同学习
这里写图片描述

public class CountWithException{    public static void main(String[] args)    {        if (args.length != 3)        {            System.out.println("Enter x1 operation x2");            System.exit(1);        }        try        {            int x1 = parseInt(args[0]);            int x2 = parseInt(args[2]);            System.out.println(args[0] + " " + args[1] + " " + args[2] + " = " + result(x1, x2, args[1].charAt(0)));        }        catch (NumberFormatException ex)        {            System.out.println("Wrong input: " + ex.getMessage());        }    }    public static int parseInt(String str) throws NumberFormatException     {        for (int i = 0; i <  str.length(); i++)        {            if (!Character.isDigit(str.charAt(i)))            {                throw new NumberFormatException(str);            }            //System.out.println("会执行吗");        }        return Integer.parseInt(str);    }    public static int result(int x1, int x2, char operation)    {        switch (operation)        {        case '+':            return (x1 + x2);        case '-':            return (x1 - x2);        case '.':            return (x1 * x2);        case '/':            return (x1 / x2);        default :             return 0;        }    }}// 可以看出一旦抛出异常,在出现异常的方法中没有捕获和处理,就会直接中断
public class CountWithoutException{    public static void main(String [] args)    {        if (args.length != 3)        {            System.out.println("Enter x1 operation x2");            System.exit(1);        }        if (!parseInt(args[0]))        {            System.exit(2);        }        if (!parseInt(args[2]))        {            System.exit(2);        }        int x1 = Integer.parseInt(args[0]);        int x2 = Integer.parseInt(args[2]);        System.out.println(args[0] + " " + args[1] + " " + args[2] + " = " + result(x1, x2, args[1].charAt(0)));    }    public static boolean parseInt(String str)    {        for (int i = 0; i <  str.length(); i++)        {            if (!Character.isDigit(str.charAt(i)))            {                System.out.println("Wrong input : " + str);                return false;            }        }        return true;    }    public static int result(int x1, int x2, char operation)    {        switch (operation)        {        case '+':            return (x1 + x2);        case '-':            return (x1 - x2);        case '.':            return (x1 * x2);        case '/':            return (x1 / x2);        default :             return 0;        }    }}

这里写图片描述

import java.util.Scanner;public class GetSum{    public static void main(String [] args)    {        boolean succ = false;        System.out.print("Enter two Integer: ");        Scanner input = new Scanner(System.in);        while (!succ)        {            try            {                int a = input.nextInt();                int b = input.nextInt();                System.out.println(a + " + " + b + " = " + (a + b));                succ = true;            }            catch (java.util.InputMismatchException ex)            {                System.out.print("Try again. Enter two Integer: ");            }            input.nextLine();//丢弃当前输入行,可以键入新的一行        }    }}// InputMismatchException 是免检异常,但是JVM的处理方式并不是我们想要的方式// 所以我们将它的异常处理作出更改。

这里写图片描述

import java.util.Scanner;import java.util.Random;public class UseIndexFindNumber{    public static void main(String [] args)    {        Scanner input = new Scanner(System.in);        int[] numbers = creatNumberArray();        while (true)        {            try            {                System.out.print("Enter a index to find the number: ");                int index = input.nextInt();                System.out.println(numbers[index]);            }            catch (ArrayIndexOutOfBoundsException ex)            {                System.out.println("Out of Bounds");            }            input.nextLine();        }    }    public static int[] creatNumberArray()    {        Random num = new Random(9);        int[] numbers = new int[100];        for (int i = 0; i < 100; i++)        {            numbers[i] = num.nextInt(100) + 1;        }        return numbers;    }}

这里写图片描述

public class LoanUseException{    private double annualInterestRate;    private int numberOfYears;    private double loanAmount;    private java.util.Date loanDate;    public LoanUseException()    {        this(2.5, 1, 100);    }    public LoanUseException(double annualInterestRate, int numberOfYears, double loanAmount)        throws IllegalArgumentException    {        setAnnualInterestRate(annualInterestRate);        setNumberOfYears(numberOfYears);        setLoanAmount(loanAmount);        loanDate = new java.util.Date();    }    public void setAnnualInterestRate(double annualInterestRate)        throws IllegalArgumentException    {        if (annualInterestRate <= 0)        {            throw new IllegalArgumentException();        }        else            this.annualInterestRate = annualInterestRate;    }    public double getAnnualInterestRate()    {        return annualInterestRate;    }    public void setNumberOfYears(int numberOfYears)        throws IllegalArgumentException    {        if (numberOfYears <= 0)        {            throw new IllegalArgumentException();        }        else            this.numberOfYears = numberOfYears;    }    public double getNumberOfYears()    {        return numberOfYears;    }    public void setLoanAmount(double loanAmount)        throws IllegalArgumentException    {        if (loanAmount <= 0)        {            throw new IllegalArgumentException();        }        else            this.loanAmount = loanAmount;    }    public double getLoanAmount()    {        return loanAmount;    }    public double getMonthlyPayment()    {        double monthlyInterestRate = annualInterestRate / 1200;        double monthlyPayment = loanAmount * monthlyInterestRate / (1 -             (1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12)));        return monthlyPayment;    }    public double getTotalPayment()    {        double totalPayment = getMonthlyPayment() * numberOfYears * 12;        return totalPayment;    }    public java.util.Date getLoanDate()    {        return loanDate;    }}

这里写图片描述

public class IllegalTriangleException extends Exception{    private double side1;    private double side2;    private double side3;    public IllegalTriangleException(double side1, double side2, double side3)    {        super("Invaoide sides " + side1 + " " + side2 + " " + side3);        this.side1 = side1;        this.side2 = side2;        this.side3 = side3;    }    public double getSide1()    {        return side1;    }    public double getSide2()    {        return side2;    }    public double getSide3()    {        return side3;    }}// 异常类在书写的时候就是一个正常的类
public class TriangleUseIllegalTrianglException{    private double side1;    private double side2;    private double side3;    public TriangleUseIllegalTrianglException()        throws IllegalTriangleException    {        this(1.0, 1.0, 1.0);    }    public TriangleUseIllegalTrianglException(double side1, double side2, double side3)        throws IllegalTriangleException    {        setSides(side1, side2, side3);    }    public void setSides(double side1, double side2, double side3)        throws IllegalTriangleException    {        if ((side1 + side2 <= side3) || (side1 - side2 >= side3))        {            throw new IllegalTriangleException(side1, side2, side3);        }        else        {            this.side1 = side1;            this.side2 = side2;            this.side3 = side3;        }       }    public void setSide1(double side1) throws IllegalTriangleException    {        setSides(side1, this.side2, this.side3);    }    public void setSide2(double side2) throws IllegalTriangleException    {        setSides(this.side1, side2, this.side3);    }    public void setSide3(double side3) throws IllegalTriangleException    {        setSides(this.side1, this.side2, side3);    }    public double getSide1()    {        return side1;    }    public double getSide2()    {        return side2;    }    public double getSide3()    {        return side3;    }    public double getArea()    {        double s = (side1 + side2 + side3) / 2;        return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));    }    public double getPerimeter()    {        return (side1 + side2 + side3);    }}
import java.util.Scanner;public class TestTriangleUseIllegalTrianglException{    public static void main(String [] args)    {        Scanner input = new Scanner(System.in);        while (true)        {            System.out.print("Enter three sides for a triangle: ");            try            {                double side1 = input.nextDouble();                double side2 = input.nextDouble();                double side3 = input.nextDouble();                TriangleUseIllegalTrianglException triangle =                     new TriangleUseIllegalTrianglException(side1, side2, side3);                System.out.println("The area is " + triangle.getArea());                System.out.println("The perimeter is " + triangle.getPerimeter());            }            catch (IllegalTriangleException ex)            {                System.out.println(ex.getMessage());                System.out.println("Try again.");            }            input.nextLine();        }    }}

这里写图片描述

import java.util.Scanner;public class HexToDecUseException{    public static void main(String [] args)    {        Scanner input = new Scanner(System.in);        try        {            System.out.print("Enter a hex number: ");            String hexString = input.next();            int decNumber = hexToDex(hexString);            System.out.println("The decimal value for hex number "                 + hexString + " is " + decNumber);        }        catch (NumberFormatException ex)        {            System.out.println(ex.toString() + " not a hex string.");        }    }    public static int hexToDex(String hexString) throws NumberFormatException    {        int result = 0;        for (int i = hexString.length() - 1; i >= 0; i--)        {            int judge = judge(hexString.charAt(i));            if (judge == -1)            {                throw new NumberFormatException(hexString);            }            else                result += judge * Math.pow(16, (hexString.length() - i - 1));        }        return result;    }    public static int judge(char ch)    {        if (ch >= '0' && ch <= '9')        {            return (ch - '0');        }        else if (ch >= 'A' && ch <= 'F')        {            return (ch - 'A' + 10);        }        else            return -1;    }}
阅读全文
0 0
原创粉丝点击