Java程序设计梁勇第十版第十二章编程练习题

太多私信要我继续更新,之前我是看到12章大概,所以我就只更新12章和以后的章节。如果有需要其他章节的代码可以私聊我和底下留言

Practice 12_1

public static void main(String[] args) {
		args = new String[] {"4x", "+", "56"};  // 这里只演示错误的类型
		
		System.out.print("Java Calculator ");   // 打印标题
		for (int n = 0; n < args.length; n++)   // 打印题目 
			System.out.print(args[n] + " ");
		System.out.println();
		
		// Check number of Strings passed
		if (args.length != 3) {                 
			System.out.println(
					"Usage: java Calculator operand1 operator operand2");
			System.exit(0);
		}
		
		// The result of the operation
		int result = 0;
		
		try {
			// Determine the operator
			switch (args[1].charAt(0)) {
				case '+': result = Integer.parseInt(args[0]) + Integer.parseInt(args[2]);
						break;
				case '-': result = Integer.parseInt(args[0]) - Integer.parseInt(args[2]);
						break;
				case '.': result = Integer.parseInt(args[0]) * Integer.parseInt(args[2]);
						break;
				case '/': result = Integer.parseInt(args[0]) / Integer.parseInt(args[2]);
			}
			
			// Display result  
			// 这里其实也是在程序没有异常的时候,程序正常进行
			System.out.println(args[0] + ' ' + args[1] + ' ' + args[2]  + " = " + result);
		}
		
		// 捕获一个ArithmeticException
		catch (ArithmeticException ex) {  
			System.out.println("Wrong Input: " + args[2] + " cannot zero ");
		}
		// 捕获一个数据类型格式异常
		catch (java.lang.NumberFormatException ex) {  
			System.out.println("Wrong Input: " + ex);
		}
	}

Practice 12_2

public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		
		boolean boo = true;
		do {
			try {
				// 输入两个数
				System.out.print("Please input two integers: ");
				int number1 = input.nextInt();
				int number2 = input.nextInt();
				
				// 两数之和
				int sum = number1 + number2;
				// 打印正常程序运行的结果
				System.out.println(number1 + " + " + number2 + " = " + sum);
				boo = false;  // 程序正常则终止循环
			}
			
			// 捕获一个InputMismatchExcption
			catch(java.util.InputMismatchException ex) {
				// 告知用户异常原因
				System.out.println("Wrong input, and please input again!");
				input.nextLine();
			} 

		} while (boo); // 循环条件
	}

Practice 12_3

public static void main (String[] args) {
		// 创建100个数范围的数组
		int[] randomNumberArray = new int[100];
		
		for (int i = 0; i < randomNumberArray.length; i++) 
			// 产生一些随机数,我自己定义在100以内,
			randomNumberArray[i] = (int)(Math.random() * 100);
		
		Scanner input = new Scanner(System.in);
		
		System.out.print("Please input a index of the array: ");
		try {
			int number = input.nextInt();	
			System.out.println("Input element is " + randomNumberArray[number]);
		}
		
		catch (java.util.InputMismatchException ex) {
			// 这里是看你要不要写这个异常, 我觉得是有必要的,如果你单纯做这个题目可能题目不要求
			System.out.println("Wrong input!");
		}
		
		catch (ArrayIndexOutOfBoundsException ex) {
			// 这里我想说题目好像没有Of, 我尝试了没加Of,我用编译器eclipse和idea都没有对应的函数
			System.out.println("Out of Bounds");
		}
		
		
		// 最后我想说的是,如果想程序更完美点,可以加个循环,但是题目没要求
	}

Practice 12_4

public class TestIllegalArgumentExceptionDemo {
	public static void main(String[] args) {
		// 这里需要各位自己输入数据演示一下 我自己程序演示正常
	}
}

class IllegalArgumentExceptionDemo {
	private double annualInterestRate;
	private int numberOfYears;	
	private double loanAmount;
	private java.util.Date loanDate;
	
	/** Default constructor */
	
	public IllegalArgumentExceptionDemo() {
		this(2.5, 1, 100);
	}
	
	/** Construct a loan with specified annual interest rate,
	 * number of years, and loan amount
	 * @param annualInterestRate
	 * @param numberOfYears
	 * @param loanAmount
	 */
	public IllegalArgumentExceptionDemo(double annualInterestRate, int numberOfYears, double loanAmount) throws IllegalArgumentException {
		// 我觉得是用if-else 比较合适,因为是可预知的
		// 反而这里try-catch程序不太好看 , 以下同理
		if(annualInterestRate > 0 && numberOfYears > 0 && loanAmount > 0) {
			this.annualInterestRate = annualInterestRate;
			this.numberOfYears = numberOfYears;
			this.loanAmount = loanAmount;
		}
		else throw new IllegalArgumentException ("They neither cannot less or equal to zero"
					+ " by annualInterestRate, numberOfYears or loanAmount");
		loanDate = new java.util.Date();
	}
	
	/** Return annualInterestRate */
	public double getAnnualInterestRate() {
		return annualInterestRate;
	}
	
	/** Set a new annualInterestRate 
	 * @throws Exception */
	public void setAnnualInterestRate(double annualInterestRate) throws illegalArgumentException {
		if (annualInterestRate > 0)
			this.annualInterestRate = annualInterestRate;
		else throw new IllegalArgumentException ("annualInterestRate cannot less than or equal to zero");
	}

	/** Return numberOfYears */
	public int getNumberOfYears() {
		return numberOfYears;
	}
	
	/** Set a new numberOfYears */
	public void setNumberOfYears(int numberOfYears) throws IllegalArgumentException {
		if (numberOfYears > 0)
			this.numberOfYears = numberOfYears;
		else
			throw new IllegalArgumentException ("NumberOfYeas cannot less than or equal to zero");
	}
	
	/** Return loanAmount */
	public double getLoanAmount() {
		return loanAmount;
	}
	
	/** Set a new loanAmount */
	public void setLoanAmount(double loanAmount) throw IllegalArgumentExcption {
		if (loanAmount > 0)
			this.loanAmount = loanAmount;
		else throw new IllegalArgumentException ("LoanAmount cannot less than ro equal to zero");
	}
	
	/** Find monthly payment */
	public double getMonthlyPayment() {
		double monthlyInterestRate = annualInterestRate / 1200;
		double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 
				(1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12)));
		return monthlyPayment;
	}
	
	/** Find total payment */
	public double getTotalPayment() {
		double totalPayment = getMonthlyPayment() * numberOfYears * 12;
		return totalPayment;
	}
	
	/** Return loan date */
	public java.util.Date getLoanDate() {
		return loanDate;
	}
	
}

Practice12_5

public class TestTriangle {
	public static void main(String[] args) {
		
	}
}

class Triangle extends SimpleGeometricObject{
	private double side1;
	private double side2;
	private double side3;
	
	public Triangle() {
		side1 = 1.0;
		side2 = 1.0;
		side3 = 1.0;
	}
	
	public Triangle(double side1, double side2, double side3) throws IllegalArgumentException{ 
		if (side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1) {
			this.side1 = side1;
			this.side2 = side2;
			this.side3 = side3;
		}
		else throw new IllegalArgumentException("The input sides cannot form a triangle");
	}
	
	public void setSide1(double side1) {
		this.side1 = side1;
	}
	
	public double getSide1() {
		return side1;
	}
	
	public void setSide2(double side2) {
		this.side2 = side2;
	}
	
	public double getSide2() {
		return side2;
	}
	
	public void setSide3(double side3) {
		this.side3 = side3;
	}
	
	public double getSide3() {
		return side3;
	}
	
	 public double getArea() {
         double n = side1 + side2 + side3;
         return Math.sqrt(n * (n - side1) * (n - side2) * (n - side3));
	 }

	 public double getPerimeter() {
         return side1 + side2 + side3;
	 }

	 @Override
	 public String toString() {
		 return "TestTriangle{" +
             "side1=" + side1 +
             ", side2=" + side2 +
             ", side3=" + side3 +
             '}';
	 }
}

class SimpleGeometricObject {
	private String color = "while";
    private boolean filled;
    private java.util.Date dateCreated;

    /** Construct a default geometric object */
    public SimpleGeometricObject() {
        dateCreated = new java.util.Date();
    }

    /** Construct a geometric object with the specified color
     * and fill value
     */
    public SimpleGeometricObject(String color, boolean filled) {
        dateCreated = new java.util.Date();
        this.color = color;
        this.filled = filled;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public boolean isFilled() {
        return filled;
    }

    public void setFilled(boolean filled) {
        this.filled = filled;
    }

    public java.util.Date getDateCreated() {
        return dateCreated;
    }

    public String toString() {
        return "SimpleGeometricObject{" +
                "color='" + color + '\'' +
                ", filled=" + filled +
                ", dateCreated=" + dateCreated +
                '}';
    }
	
}

Practice 12_6

	public static void main(String[] args) {
		// Create a Scanner
		Scanner input = new Scanner(System.in);
		
		// Prompt the user to enter a String
		System.out.print("Enter a hex number: ");
		String hex = input.nextLine();
		
		System.out.println("The decimal value for hex number " + hex
				+ " is " + hexToDecimal(hex.toUpperCase()));
	}
	
	public static int hexToDecimal(String hex) {
		int decimalValue = 0;
		for (int i = 0; i < hex.length(); i++) {
			char hexChar = hex.charAt(i);
			decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
		}
		
		return decimalValue;
	}
	
	/** 这题目也就是这里的静态方法中修改一下,除了1—9,A-F(小写大写都可以)
	/* 的字符都不符合十六进制的格式标准,所以会引发异常,下面一个题目也是
	/* 一样的道理,我这里就不再写的,直接略过
	*/
	public static int hexCharToDecimal(char ch) throws java.lang.NumberFormatException { 
		if (ch >= 'A' && ch <= 'F')
			return 10 + ch - 'A';
		else if (ch >= '0' && ch <= '9') // ch is '0', '1', ...... or '9'
			return ch - '0';
		else throw new java.lang.NumberFormatException("您输入的数不是十六进制的数");
	}

Practice 12_8

public class NumberFormatExceptionDemo {
	public static void main(String[] args) throws HexFormatException_1 {
		// Create a Scanner
		Scanner input = new Scanner(System.in);
		
		// Prompt the user to enter a String
		System.out.print("Enter a hex number: ");
		String hex = input.nextLine();
		
		System.out.println("The decimal value for hex number " + hex
				+ " is " + hexToDecimal(hex.toUpperCase()));
	}
	
	public static int hexToDecimal(String hex) throws HexFormatException_1 {
		int decimalValue = 0;
		for (int i = 0; i < hex.length(); i++) {
			char hexChar = hex.charAt(i);
			decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
		}
		
		return decimalValue;
	}
	
	public static int hexCharToDecimal(char ch) throws HexFormatException_1 {
		if (ch >= 'A' && ch <= 'F')
			return 10 + ch - 'A';
		else if (ch >= '0' && ch <= '9')	// ch is '0', '1', ...... or '9'
			return ch - '0';
		else throw new HexFormatException_1(ch);
	}
}
// 这里是自定义的一个异常类,异常类看你自己怎么定义,能打印捕获异常的异常信息就可以
class HexFormatException_1 extends Exception{
	private char ch;
	
	HexFormatException_1(char ch) {
		super("您输入的输入不是十六进制的数" + ch);
		this.ch = ch;
	}
	
	public char getCh() {
		return ch;
	}
}

Practice12_9 略过

Practice12_10
OutofMemoryError 有很多种方式导致,比较简单,如何你实在不会列举,你列举一个无限循环也可以。

Practice12_11

这题略吧,代码没找到,利用StringBuilder,先把数据放入StringBuilder,再用replace或者replaceAll进行替换,替换好了,再用PrintWriter 读出StringBuilder里面的数据

Practice12_13
这个题目想略的,也没想写注释,应该都没有什么疑问吧。

public static void main(String[] args) throws Exception {
		File file = new File("Temp09.txt");
		
		try(
			Scanner input = new Scanner(file);
			Scanner input1 = new Scanner(file);
				) {
			int count1 = 0;
			while (input.hasNext()) {
				String word = input.next();
				count1++;
			}
			int count2 = 0;
			while (input1.hasNext()) {
				String line = input1.nextLine();
				count2++;
			}
			
			System.out.println("File " + file.getPath() + " has");
			System.out.println(file.length() + " characters");
			System.out.println(count1 + " words");
			System.out.println(count2 + " lines");
		}
	}

12_17

这题我没有依次匹配,如果你有需求的可以自己改一下

   public static void main(String[] args) throws IOException {
        // 我想说的为什么要叫刽子手的文件名,有大神告诉我还有别的意思吗
        File file = new File("hangman.txt"  );

        try {
            // PrintWriter函数创建
            PrintWriter output = new PrintWriter(file);
            // 自定义储存单词的数组
            String[] words = {"write", "that", "program", "dargon", "andy", "jason"};
            // Scanner函数创建
            Scanner input = new Scanner(System.in);

            // 这个一大段当然是y和n来控制循环,这没什么好说的吧
            String togoing = "y";
            boolean boo = true;

            while (boo) {
                // 这里随机产生一个单词,
                String guessWord = words[(int) (Math.random() * words.length)];
                // 创建一个由*填充的数组
                String[] list = new String[guessWord.length()];
                Arrays.fill(list, "*");

                // 创建一个想要储存guessWord的数组
                String[] list1 = new String[guessWord.length()];

                // 然后储存进去
                for (int n = 0; n < list1.length; n++) {
                    list1[n] = String.valueOf(guessWord.charAt(n));
                }

                // 这里的times是用来计算用户输入字母错误的次数
                int times = 0;
                // 是否全部匹配完成,如何是,就跳出该循环

                while (isAllMatchlist(list)) {
                    // 这里count是用来判断是否重复输入
                    int count = 0;
                    // 打印标题
                    System.out.print("(Guess) Enter a letter in word ");
                    displayArray(list); // 打印list
                    System.out.print(" > ");
                    // 输入的字母

                    String ch = input.next();

                    for (int i = 0; i < list.length; i++) {
                        // 这里打印重复输入的标题,如果重复字母,跳出循环,并计数
                        if (list[i].equals(ch)) {
                            System.out.println(ch + " is already in the word");
                            count++;
                            break;
                        }

                        // 这里是猜对的字母赋值到list中,因为标题要不断的更新list
                        if (list1[i].equals(ch)) {
                            count++;
                            list[i] = ch;
                        }
                    }

                    // 如果count没有超过0 就是说明输入的字母不是所猜的字母,打印标题,再计数
                    if (count <= 0) {
                        System.out.println(ch + " is not in the word");
                        times++;
                    }

                }

                // 打印
                System.out.print("The word is ");
                displayArray(list);
                System.out.println(". You missed " + times +
                        ((times > 1) ? " times" : " time"));

                // 打完全猜好的单词放入hangman.txt中 并附题目要求用空格隔开
                output.print(guessWord + " ");

                // 判断是否继续读入单词
                System.out.print("Do you want to guess another word? Enter y or n> ");
                String line = input.nextLine();
                togoing = input.next();
                
                if (togoing.equals("Y") || togoing.equals("y"))
                    boo = true;
                else if (togoing.equals("N") || togoing.equals("n"))
                    boo = false;
                else
                    throw new InputMismatchException();
            }
            output.close();

        }
        catch (InputMismatchException ex) {
            System.out.println("Input wrong!" + ex.getMessage());
        }
        catch (IOException ex) {
            System.out.println("Error!" + ex.toString());

        }

    }

    /** list的内容的打印*/
    public static void displayArray(String[] list) {
        for (String str : list) {
            System.out.print(str);
        }
    }
    /** 判断list1是否匹配完成*/
    public static boolean isAllMatchlist(String[] list) {

        for (int n = 0; n < list.length; n++) {
            if (list[n].equals("*"))
                return true;
        }
        return false;
    }

12_18

	public static void main(String[] args) throws IOException {
		// 设置一个根目录
        File file = new File("srcRootDirectory");
        file.mkdir();

        // 设置34个chapter都再根目录下面
        // 然后chapter里面都装有一个java源文件,源文件里有个java程序
        for (int n = 1; n < 35; n++)  {
            String s = "chapter" + n;
            File file_1 = new File("srcRootDirectory/" + s);
            file_1.mkdir();

            String s1 = "test"+n+".java";
            File file_2 = new File("srcRootDirectory/" + s + "/" + s1);
            PrintWriter output = new PrintWriter(file_2);
            output.println("public class test" + n + " {");
            output.println("    public static void main(String[] args) {");
            output.println("        System.out.println(\"Hello World\")");
            output.println("    }");
            output.println("}");
            output.close();
        }

        // 每个chapter里面首行再进行添加一个 package chapteri
        StringBuilder stringBuilder = new StringBuilder();
        for (int n = 1; n < 35; n++) {
            String s = n + "/test"+n+".java";
            File file_1 = new File("srcRootDirectory/chapter" + s);
            stringBuilder.append("package chapter"+n + "\r\n");
            Scanner input = new Scanner(file_1);
            while(input.hasNext()) {
                String line = input.nextLine();
                stringBuilder.append(line+ "\r\n");
            }
            input.close();
            PrintWriter output = new PrintWriter(file_1);
            output.append(stringBuilder);
            output.close();
        }
    }

12_30

    public static void main(String[] args) throws Exception {
        Scanner input = new Scanner(System.in);

        // 可以自己设置一个文件测试一下
        System.out.print("Enter a filename: ");
        String filename = input.nextLine();

        File file = new File(filename);
		// 如果输入的文件不存在,说明filename不正确,引发一个异常
        if (!file.exists())
            throw new Exception("file no exist!");
            
        // 设置一个二维数组,第一列是打印大写字母 A-Z,第二列是 在文件出现的次数;
        String[][] list = new String[26][2];
        for (int n = 0; n < list.length; n++) {
            list[n][0] = (char) ('A' + n) + "";
            list[n][1] = 0+""; // 先把次数都设为0次
        }

        Scanner input1 = new Scanner(file);
        while(input1.hasNext()) {
            String str = input1.next(); // 这里你可以每个单词读取,也可以每行读取,用nextLine()

            for (int n = 0; n < str.length(); n++) {
                // 先判断提取的字符是否为大写
                if (IsUpperLetter(str.charAt(n))) {
                    for (int m = 0; m < list.length; m++) {
                        // 查找具体哪个大写后,对出现次数进行计算
                        if (str.charAt(n) == list[m][0].charAt(0)) {
                            list[m][1] = Integer.parseInt(list[m][1]) + 1 +"";
                        }
                    }
                }
            }
        }
        input1.close(); // 这个记得关闭

        // 然后用循环打印
        for (String[] a : list) 
            System.out.println("Number of " + a[0] + "'s: " + a[1]);
        
    }

    /** 这里是判断一个字符是否为大写的方法 */
    public static boolean IsUpperLetter(char ch) {
        if (ch >= 'A' && ch <= 'Z')
            return true;
        return false;
    }
  • 11
    点赞
  • 57
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值