JAVA语言程序设计基础篇(Chapter 12)课后习题参考答案

1. (简答题)

(ArrayIndexOutOfBoundsException) Write a program using exception handling. The program needs to meet the following requirements: 

■ Creates an array with 100 randomly chosen integers. 

■ Prompts the user to enter the index of the array, then displays the corresponding element value. If the specified index is out of bounds, display the  message Out of Bounds.

import java.util.Scanner;

public class OutOfBoundsTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] array = getArray();
        System.out.print("Enter the index of the array:");
        try {
            System.out.println("The corresponding element value is " + array[sc.nextInt()]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Out of Bounds.");
        }
    }

    public static int[] getArray() {
        int[] array = new int[100];
        for (int i = 0; i < array.length; i++) {
            array[i] = (int) (Math.random() * 100) + 1;
        }
        return array;
    }
}

2. (简答题)

(IllegalTriangleException) Programming Exercise 11.1 defined the  Triangle class with three sides. In a triangle, the sum of any two sides is  greater than the other side. The Triangle class must adhere to this rule.  Create the IllegalTriangleException class, and modify the constructor  of the Triangle class to throw an IllegalTriangleException object if a  triangle is created with sides that violate the rule, as follows: 

   /** Construct a triangle with the specified sides */

   public Triangle(double side1, double side2, double side3) 

      throws IllegalTriangleException { 

        // Implement it 

  }

Note: You can get the information about Programming Exercise 11.1 at the end of Chapter 11 in the textbook.

A test program is given below. Please complete the whole program.

public class Test {

  public static void main(String[] args) {

    try {

      Triangle t1 = new Triangle (1.5, 2, 3);

      System.out.println("Perimeter for t1: " + t1.getPerimeter());

      System.out.println("Area for t1: " + t1.getArea());

      

      Triangle t2 = new Triangle (1, 2, 3);

      System.out.println("Perimeter for t2: " + t2.getPerimeter());

      System.out.println("Area for t2: " + t2.getArea());

    }

    catch (IllegalTriangleException ex) {

      System.out.println("Illegal triangle");

      System.out.println("Side1: " + ex.getSide1());

      System.out.println("Side2: " + ex.getSide2());

      System.out.println("Side3: " + ex.getSide3());

    }

  }

}

class IllegalTriangleException extends Exception {

   // Implement it

}

class Triangle extends GeometricObject {

  double side1, side2, side3;

//Modify the constructor of the Triangle Class

  public Triangle (double side1, double side2, double side3) throws IllegalTriangleException {

// Implement it

  }

  //In order to make the Test class run successfully, you should add the definitions of the left methods in the class Triangle.

  // The UML notation for the class Triangle is given in Programming Exercise 11.1

 // And don't forget to define the super class GeometricObject

 }

public class Test {
  public static void main(String[] args) {
    try {
      Triangle t1 = new Triangle (1.5, 2, 3);
      System.out.println("Perimeter for t1: " + t1.getPerimeter());
      System.out.println("Area for t1: " + t1.getArea());
      Triangle t2 = new Triangle (1, 2, 3);
      System.out.println("Perimeter for t2: " + t2.getPerimeter());
      System.out.println("Area for t2: " + t2.getArea());
    }
    catch (IllegalTriangleException ex) {
      System.out.println("Illegal triangle");
      System.out.println("Side1: " + ex.getSide1());
      System.out.println("Side2: " + ex.getSide2());
      System.out.println("Side3: " + ex.getSide3());
    }
  }
}
// Please implement the IlleagalTriangleException class
class IllegalTriangleException extends Exception {
    private double side1;
    private double side2;
    private double side3;
    public IllegalTriangleException(double side1,double side2,double side3){
        super("Invalid side "+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;
    }
}
// Please modify the Triangle class
class Triangle extends GeometricObject {
    private double side1 = 1.0;
    private double side2 = 1.0;
    private double side3 = 1.0;
    public Triangle() {
    }
    public Triangle(double side1, double side2, double side3)throws IllegalTriangleException {
        if ((side1+side2)>side3&(side1+side3)>side2&(side2+side3)>side1) {
            this.side1 = side1;
            this.side2 = side2;
            this.side3 = side3;
        } else {
            throw new IllegalTriangleException(side1,side2,side3);
        }
    }
    public double getSide1() {
        return side1;
    }
    public double getSide2() {
        return side2;
    }
    public double getSide3() {
        return side3;
    }
    public double getArea() {
        double p = (side1 + side2 + side3) / 2;
        double area = Math.sqrt(p * (p - side1) * (p - side2) * (p - side3));
        return area;
    }
    public double getPerimeter() {
        return side1 + side2 + side3;
    }
    @Override
    public String toString() {
        return "Triangle:" +
                "side1 = " + side1 +
                ", side2 = " + side2 +
                ", side3 = " + side3;
    }

}
// Implement the GeometricObject class as well.
class GeometricObject{
private String color = "white";
    private boolean filled;
    private Date dateCreated;
    public GeometricObject() {
        this.dateCreated = new Date();
    }
    public GeometricObject(String color, boolean filled) {
        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 Date getDateCreated() {
        return dateCreated;
    }
    @Override
    public String toString() {
        return "GeometricObject{" +
                "color='" + color + '\'' +
                ", filled=" + filled +
                ", dateCreated=" + dateCreated +
                '}';
    }

}

3. (简答题)

(Remove text) Write a program that removes all the occurrences of a specified  string from a text file. For example, invoking 

        java   RemoveText   John   filename 

removes the string John from the specified file. Your program should get the  arguments from the command line.

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public class RemoveString {
    public static void main(String[] args) throws Exception {
        if (args.length != 2) {
            System.out.println("Usage: java RemoveTest filename");
            System.exit(1);
        }
        File file = new File(args[1]);
        if (!file.exists()) {
            System.out.println("File " + args[1] + " does not exist");
            System.exit(2);
        }
        ArrayList<String> s = new ArrayList<>();

        Scanner sc = new Scanner(file);
        while (sc.hasNext()) {
            String s1 = sc.nextLine();
            s.add(removeString(args[0], s1));
        }
        sc.close();
        PrintWriter printWriter = new PrintWriter(args[1]);
        for (int i = 0; i < s.size(); i++) {
            printWriter.println(s.get(i));
        }
        printWriter.close();
    }

    public static String removeString(String string, String line) {
        StringBuilder stringBuilder = new StringBuilder(line);
        int start = stringBuilder.indexOf(string);
        int end = string.length();
        while (start >= 0) {
            end = start + end;
            stringBuilder = stringBuilder.delete(start, end);
            start = stringBuilder.indexOf(string, start);
        }
        return stringBuilder.toString();
    }
}

4. (简答题)

(Replace text) Write a program that replaces  text in a source file and  save the change into the original file. For example, invoking 

    java ReplaceText file oldString newString 

replaces oldString in the source file with newString.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class ReplaceStringTest {
    public static void main(String[] args) throws FileNotFoundException {
        if (args.length != 3) {
            System.out.println("Usage: Java Exercise_12_16 file oldString new String");
            System.exit(1);
        }
        File file = new File(args[0]);
        if (!file.exists()) {
            System.out.println("File " + args[0] + " does not exist");
            System.exit(2);
        }
        ArrayList<String> list = new ArrayList<>();
        try (
                Scanner sc = new Scanner(file);
        ) {
            while (sc.hasNext()) {
                String s = sc.nextLine();
                list.add(s.replaceAll(args[1], args[2]));
            }

        }
        try (
                PrintWriter printWriter = new PrintWriter(file)
        ) {
            for (int i = 0; i < list.size(); i++) {
                printWriter.println(list.get(i));
            }
        }
    }

}

5. (简答题)

(Occurrences of each letter) Write a program that prompts the user to enter  a file name and displays the occurrences of each letter in the file. Letters are  case-insensitive. Here is a sample run:

       Enter a filename: Lincoln.txt 

       Number of A's: 56  

       Number of B's: 134  

        ... 

       Number of Z's: 9

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class OccurrenceTest {
    public static void main(String[] args) throws FileNotFoundException {
        File file = new File(getFileName());
        if (!file.exists()) {
            System.out.println("File " + file.getName() + " does not exist");
            System.exit(0);
        }
        int[] count = new int[26];
        try (
                Scanner sc = new Scanner(file);
        ) {
            while (sc.hasNext()) {
                String s = (sc.nextLine()).toUpperCase();
                countLetters(count, s);
            }
        }
        for (int i = 0; i < count.length; i++) {
            System.out.println("Number of " + (char) ('A' + i) + "'s: " + count[i]);
        }
    }

    public static void countLetters(int[] count, String str) {
        for (int i = 0; i < str.length(); i++) {
            if (Character.isLetter(str.charAt(i))) {
                count[(int) (str.charAt(i) - 'A')]++;
            }
        }
    }

    public static String getFileName() {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a filename : ");
        return sc.next();
    }
}

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值