搜索
您的当前位置:首页正文

java语言程序设计基础篇第十版第十三章练习答案

来源:知库网
01

public class Exercise13_01 {

public static void main(String[] args) {

TriangleNew triangle = new TriangleNew(1, 1.5, 1); triangle.setColor(\"yellow\"); triangle.setFilled(true);

System.out.println(triangle);

System.out.println(\"The area is \" + triangle.getArea()); System.out.println(\"The perimeter is \" + triangle.getPerimeter()); System.out.println(triangle); } }

class TriangleNew extends GeometricObject {

private double side1 = 1.0, side2 = 1.0, side3 = 1.0;

/** Constructor */ public TriangleNew() { }

/** Constructor */

public TriangleNew(double side1, double side2, double side3) { this.side1 = side1; this.side2 = side2; this.side3 = side3; }

/** Implement the abstract method findArea in GeometricObject */ public double getArea() {

double s = (side1 + side2 + side3) / 2;

return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3)); }

/** Implement the abstract method findCircumference in * GeometricObject **/

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

@Override

public String toString() {

// Implement it to return the three sides

return \"TriangleNew: side1 = \" + side1 + \" side2 = \" + side2 + \" side3 = \" + side3; } } 02

import java.util.ArrayList; public class Exercise13_02 {

public static void main(String[] args) {

ArrayList list = new ArrayList(); list.add(14); list.add(24); list.add(4); list.add(42); list.add(5); shuffle(list);

for (int i = 0; i < list.size(); i++) System.out.print(list.get(i) + \" \"); }

public static void shuffle(ArrayList list) { for (int i = 0; i < list.size() - 1; i++) {

int index = (int)(Math.random() * list.size()); Number temp = list.get(i); list.set(i, list.get(index)); list.set(index, temp); } } } 03

import java.util.ArrayList;

public class Exercise13_03 {

public static void main(String[] args) {

ArrayList list = new ArrayList(); list.add(14); list.add(24); list.add(4); list.add(42); list.add(5); sort(list);

for (int i = 0; i < list.size(); i++)

System.out.print(list.get(i) + \" \"); }

public static void sort(ArrayList list) { for (int i = 0; i < list.size() - 1; i++) {

// Find the minimum in the list[i..list.length-1] Number currentMin = list.get(i); int currentMinIndex = i;

for (int j = i + 1; j < list.size(); j++) {

if (currentMin.doubleValue() > list.get(j).doubleValue()) { currentMin = list.get(j); currentMinIndex = j; } }

// Swap list.get(i) with list.get(currentMinIndex) if necessary; if (currentMinIndex != i) {

list.set(currentMinIndex, list.get(i)); list.set(i, currentMin); } } } } 04

import java.util.*;

public class Exercise13_04 {

static MyCalendar calendar = new MyCalendar();

public static void main(String[] args) {

int month = calendar.get(MyCalendar.MONTH) + 1; int year = calendar.get(MyCalendar.YEAR);

if (args.length > 2)

System.out.println(\"Usage java Exercise13_04 month year\"); else if (args.length == 2) {

//use user-defined month and year year = Integer.parseInt(args[1]); month = Integer.parseInt(args[0]);

calendar.set(Calendar.YEAR, year);

calendar.set(Calendar.MONTH, month - 1); }

else if (args.length == 1) {

//use user-defined month for the current year month = Integer.parseInt(args[0]);

calendar.set(Calendar.MONTH, month-1); }

//set date to the first day in a month calendar.set(Calendar.DATE, 1);

//print calendar for the month printMonth(year, month); }

static void printMonth(int year, int month) {

//get start day of the week for the first date in the month int startDay = getStartDay();

//get number of days in the month

int numOfDaysInMonth = calendar.daysInMonth();

//print headings

printMonthTitle(year, month);

//print body

printMonthBody(startDay, numOfDaysInMonth); }

static int getStartDay() {

return calendar.get(Calendar.DAY_OF_WEEK); }

static void printMonthBody(int startDay, int numOfDaysInMonth) { //print padding space before the first day of the month int i = 0;

for (i = 0; i < startDay-1; i++) System.out.print(\" \");

for (i = 1; i <= numOfDaysInMonth; i++) { if (i < 10)

System.out.print(\" \"+i); else

System.out.print(\" \"+i);

if ((i + startDay - 1) % 7 == 0) System.out.println(); }

System.out.println(\"\"); }

static void printMonthTitle(int year, int month) {

System.out.println(\" \"+calendar.getMonthName()+\ System.out.println(\"-----------------------------\");

System.out.println(\" Sun Mon Tue Wed Thu Fri Sat\"); } } 05

public class Exercise13_05 { // Main method

public static void main(String[] args) { // Create two comparable circles Circle1 circle1 = new Circle1(5); Circle1 circle2 = new Circle1(4);

// Display the max circle

Circle1 circle = (Circle1) GeometricObject1.max(circle1, circle2); System.out.println(\"The max circle's radius is \" + circle.getRadius()); System.out.println(circle); } }

abstract class GeometricObject1 implements Comparable { protected String color; protected double weight;

// Default construct

protected GeometricObject1() { color = \"white\"; weight = 1.0; }

// Construct a geometric object

protected GeometricObject1(String color, double weight) { this.color = color; this.weight = weight;

}

// Getter method for color public String getColor() { return color; }

// Setter method for color

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

// Getter method for weight public double getWeight() { return weight; }

// Setter method for weight

public void setWeight(double weight) { this.weight = weight; }

// Abstract method

public abstract double getArea();

// Abstract method

public abstract double getPerimeter();

public int compareTo(GeometricObject1 o) { if (getArea() < o.getArea()) return -1;

else if (getArea() == o.getArea()) return 0; else

return 1; }

public static GeometricObject1 max(GeometricObject1 o1, GeometricObject1 o2) { if (o1.compareTo(o2) > 0) return o1; else

return o2; } }

// Circle.java: The circle class that extends GeometricObject class Circle1 extends GeometricObject1 { protected double radius;

// Default constructor public Circle1() {

this(1.0, \"white\ }

// Construct circle with specified radius public Circle1(double radius) { super(\"white\ this.radius = radius; }

// Construct a circle with specified radius, weight, and color public Circle1(double radius, String color, double weight) { super(color, weight); this.radius = radius; }

// Getter method for radius public double getRadius() { return radius; }

// Setter method for radius

public void setRadius(double radius) { this.radius = radius; }

// Implement the findArea method defined in GeometricObject public double getArea() {

return radius * radius * Math.PI; }

// Implement the findPerimeter method defined in GeometricObject public double getPerimeter() { return 2 * radius * Math.PI; }

// Override the equals() method defined in the Object class public boolean equals(Circle1 circle) {

return this.radius == circle.getRadius(); }

@Override

public String toString() {

return \"[Circle] radius = \" + radius; }

@Override

public int compareTo(GeometricObject1 o) { if (getRadius() > ((Circle1) o).getRadius()) return 1;

else if (getRadius() < ((Circle1) o).getRadius()) return -1; else

return 0; } } 06

public class Exercise13_06 { // Main method

public static void main(String[] args) { // Create two comarable rectangles

ComparableCircle circle1 = new ComparableCircle(5); ComparableCircle circle2 = new ComparableCircle(15);

// Display the max rect

ComparableCircle circle3 = (ComparableCircle)Max.max(circle1, circle2); System.out.println(\"The max circle's radius is \" + circle3.getRadius()); System.out.println(circle3); } }

class ComparableCircle extends Circle implements Comparable { /** Construct a ComparableRectangle with specified properties */ public ComparableCircle(double radius) { super(radius); }

@Override

public int compareTo(ComparableCircle o) { if (getRadius() > o.getRadius()) return 1;

else if (getRadius() < o.getRadius()) return -1; else

return 0; } }

//Max.java: Find a maximum object class Max {

/** Return the maximum of two objects */ public static ComparableCircle max

(ComparableCircle o1, ComparableCircle o2) { if (o1.compareTo(o2) > 0) return o1; else

return o2; } } 07

public class Exercise13_07 {

public static void main(String[] args) {

GeometricObject[] objects = {new Square(2), new Circle(5), new Square(5), new Rectangle(3, 4), new Square(4.5)};

for (int i = 0; i < objects.length; i++) {

System.out.println(\"Area is \" + objects[i].getArea()); if (objects[i] instanceof Colorable)

((Colorable)objects[i]).howToColor(); } } }

interface Colorable { void howToColor(); }

class Square extends GeometricObject implements Colorable { private double side;

public Square(double side) { this.side = side; }

@Override

public void howToColor() {

System.out.println(\"Color all four sides\"); }

@Override

public double getArea() { return side * side; }

@Override

public double getPerimeter() { return 4 * side; } } 08

import java.util.ArrayList;

public class Exercise13_08 {

public static void main(String[] args) { MyStack1 stack = new MyStack1(); stack.push(\"S1\"); stack.push(\"S2\"); stack.push(\"S\");

MyStack1 stack2 = (MyStack1) (stack.clone()); stack2.push(\"S1\"); stack2.push(\"S2\"); stack2.push(\"S\");

System.out.println(stack.getSize()); System.out.println(stack2.getSize()); } }

class MyStack1 implements Cloneable {

private ArrayList list = new ArrayList();

public boolean isEmpty() { return list.isEmpty(); }

public int getSize() {

return list.size(); }

public Object peek() {

return list.get(getSize() - 1); }

public Object pop() {

Object o = list.get(getSize() - 1); list.remove(getSize() - 1); return o; }

public void push(Object o) { list.add(o); }

/** Override the toString in the Object class */ public String toString() {

return \"stack: \" + list.toString(); }

public Object clone() { try {

MyStack1 c = (MyStack1) super.clone(); c.list = (ArrayList) this.list.clone(); return c;

} catch (CloneNotSupportedException ex) { return null; } } } 09

public class Exercise13_09 {

public static void main(String[] args) { Circle13_09 obj1 = new Circle13_09(); Circle13_09 obj2 = new Circle13_09();

System.out.println(obj1.equals(obj2)); System.out.println(obj1.compareTo(obj2)); } }

// Circle.java: The circle class that extends GeometricObject

class Circle13_09 extends GeometricObject implements Comparable { private double radius;

/** Return radius */

public double getRadius() { return radius; }

/** Set a new radius */

public void setRadius(double radius) { this.radius = radius; }

/** Implement the getArea method defined in GeometricObject */ public double getArea() {

return radius * radius * Math.PI; }

/** Implement the getPerimeter method defined in GeometricObject*/ public double getPerimeter() { return 2 * radius * Math.PI; }

@Override

public String toString() {

return \"[Circle] radius = \" + radius; }

@Override

public int compareTo(Circle13_09 obj) { if (this.getArea() > obj.getArea()) return 1;

else if (this.getArea() < obj.getArea()) return -1; else

return 0; }

public boolean equals(Object obj) {

return this.radius == ((Circle13_09)obj).radius; } }

10

public class Exercise13_10 {

public static void main(String[] args) {

Rectangle13_10 obj1 = new Rectangle13_10(); Rectangle13_10 obj2 = new Rectangle13_10(); System.out.println(obj1.equals(obj2)); System.out.println(obj1.compareTo(obj2)); } }

// Rectangle.java: The Rectangle class that extends GeometricObject

class Rectangle13_10 extends GeometricObject implements Comparable { private double width; private double height;

/** Default constructor */ public Rectangle13_10() { this(1.0, 1.0); }

/** Construct a rectangle with width and height */ public Rectangle13_10(double width, double height) { this.width = width; this.height = height; }

/** Return width */

public double getWidth() { return width; }

/** Set a new width */

public void setWidth(double width) { this.width = width; }

/** Return height */

public double getHeight() { return height; }

/** Set a new height */

public void setHeight(double height) { this.height = height;

}

/** Implement the getArea method in GeometricObject */ public double getArea() { return width*height; }

/** Implement the getPerimeter method in GeometricObject */ public double getPerimeter() { return 2*(width + height); }

@Override

public String toString() {

return \"[Rectangle] width = \" + width + \" and height = \" + height; }

@Override

public int compareTo(Rectangle13_10 obj) { if (this.getArea() > obj.getArea()) return 1;

else if (this.getArea() < obj.getArea()) return -1; else

return 0; }

public boolean equals(Object obj) {

return this.getArea() == ((Rectangle13_10)obj).getArea(); } } 11

public class Exercise13_11 {

public static void main(String[] args) { Octagon a1 = new Octagon(5);

System.out.println(\"Area is \" + a1.getArea());

System.out.println(\"Perimeter is \" + a1.getPerimeter());

Octagon a2 = (Octagon)(a1.clone());

System.out.println(\"Compare the methods \" + a1.compareTo(a2)); } }

class Octagon extends GeometricObject

implements Comparable, Cloneable { private double side;

/** Construct a Octagon with the default side */ public Octagon () { // Implement it this.side = 1; }

/** Construct a Octagon with the specified side */ public Octagon (double side) { // Implement it this.side = side; }

@Override /** Implement the abstract method getArea in GeometricObject */ public double getArea() { // Implement it

return (2 + 4 / Math.sqrt(2)) * side * side; }

@Override /** Implement the abstract method getPerimeter in GeometricObject */

public double getPerimeter() { // Implement it return 8 * side; }

@Override

public int compareTo(Octagon obj) { if (this.side > obj.side) return 1;

else if (this.side == obj.side) return 0; else

return -1; }

@Override /** Implement the clone method in the Object class */ public Object clone() {

// Octagon o = new Octagon(); // o.side = this.side; // return o; //

// Implement it try {

return super.clone(); // Automatically perform a shallow copy }

catch (CloneNotSupportedException ex) { return null; } } } 12

public class Exercise13_12 {

public static void main(String[] args) { new Exercise13_12(); }

public Exercise13_12() {

GeometricObject[] a = {new Circle(5), new Circle(6),

new Rectangle13_12(2, 3), new Rectangle13_12(2, 3)};

System.out.println(\"The total area is \" + sumArea(a)); }

public static double sumArea(GeometricObject[] a) { double sum = 0;

for (int i = 0; i < a.length; i++) sum += a[i].getArea();

return sum; } }

// Rectangle.java: The Rectangle class that extends GeometricObject class Rectangle13_12 extends GeometricObject { private double width; private double height;

/** Construct a rectangle with width and height */ public Rectangle13_12(double width, double height) {

this.width = width; this.height = height; }

/**Return width*/

public double getWidth() { return width; }

/**Set a new width*/

public void setWidth(double width) { this.width = width; }

/**Return height*/

public double getHeight() { return height; }

/**Set a new height*/

public void setHeight(double height) { this.height = height; }

/**Implement the getArea method in GeometricObject*/ public double getArea() { return width*height; }

/**Implement the getPerimeter method in GeometricObject*/ public double getPerimeter() { return 2*(width + height); }

/**Override the equals method defined in the Object class*/ public boolean equals(Rectangle rectangle) { return (width == rectangle.getWidth()) && (height == rectangle.getHeight()); }

@Override

public String toString() {

return \"[Rectangle] width = \" + width + \" and height = \" + height;

} } 13

public class Exercise13_13 { /** Main method */

public static void main(String[] args) { Course1 course1 = new Course1(\"DS\"); course1.addStudent(\"S1\"); course1.addStudent(\"S2\"); course1.addStudent(\"S3\");

Course1 course2 = (Course1) course1.clone(); course2.addStudent(\"S4\"); course2.addStudent(\"S5\"); course2.addStudent(\"S6\");

System.out.println(course1.getNumberOfStudents()); System.out.println(course2.getNumberOfStudents()); } }

class Course1 implements Cloneable { private String courseName;

private String[] students = new String[100]; private int numberOfStudents;

public Course1(String courseName) { this.courseName = courseName; }

public void addStudent(String student) { students[numberOfStudents] = student; numberOfStudents++; }

public String[] getStudents() { return students; }

public int getNumberOfStudents() { return numberOfStudents; }

public String getCourse1Name() { return courseName; }

public void dropStudent(String student) { // Left as an exercise in Exercise 10.9 }

public Object clone() { try {

Course1 c = (Course1) super.clone(); c.students = new String[100];

System.arraycopy(students, 0, c.students, 0, 100); c.numberOfStudents = numberOfStudents; return c;

} catch (CloneNotSupportedException ex) { return null; } } } 14

class NewRational extends Number implements Comparable { // Data fields for numerator and denominator private long[] r = new long[2];

/**Default constructor*/ public NewRational() { this(0, 1); }

/**Construct a rational with specified numerator and denominator*/ public NewRational(long numerator, long denominator) { long gcd = gcd(numerator, denominator); this.r[0] = numerator/gcd; this.r[1] = denominator/gcd; }

/**Find GCD of two numbers*/ private long gcd(long n, long d) { long t1 = Math.abs(n); long t2 = Math.abs(d); long remainder = t1%t2;

while (remainder != 0) { t1 = t2;

t2 = remainder; remainder = t1%t2; }

return t2; }

/**Return numerator*/ public long getNumerator() { return r[0]; }

/**Return denominator*/ public long getDenominator() { return r[1]; }

/**Add a rational number to this rational*/

public NewRational add(NewRational secondNewRational) { long n = r[0]*secondNewRational.getDenominator() + r[1]*secondNewRational.getNumerator();

long d = r[1]*secondNewRational.getDenominator(); return new NewRational(n, d); }

/**Subtract a rational number from this rational*/

public NewRational subtract(NewRational secondNewRational) { long n = r[0]*secondNewRational.getDenominator() - r[1]*secondNewRational.getNumerator();

long d = r[1]*secondNewRational.getDenominator(); return new NewRational(n, d); }

/**Multiply a rational number to this rational*/

public NewRational multiply(NewRational secondNewRational) { long n = r[0]*secondNewRational.getNumerator(); long d = r[1]*secondNewRational.getDenominator(); return new NewRational(n, d); }

/**Divide a rational number from this rational*/

public NewRational divide(NewRational secondNewRational) {

long n = r[0]*secondNewRational.getDenominator(); long d = r[1]*secondNewRational.r[0]; return new NewRational(n, d); }

@Override

public String toString() { if (r[1] == 1)

return r[0] + \"\"; else

return r[0] + \"/\" + r[1]; }

/**Override the equals method*/ public boolean equals(Object parm1) {

/**@todo: Override this java.lang.Object method*/

if ((this.subtract((NewRational)(parm1))).getNumerator() == 0) return true; else

return false; }

/**Override the intValue method*/ public int intValue() {

/**@todo: implement this java.lang.Number abstract method*/ return (int)doubleValue(); }

/**Override the floatValue method*/ public float floatValue() {

/**@todo: implement this java.lang.Number abstract method*/ return (float)doubleValue(); }

/**Override the doubleValue method*/ public double doubleValue() {

/**@todo: implement this java.lang.Number abstract method*/ return r[0]*1.0/r[1]; }

/**Override the longValue method*/ public long longValue() {

/**@todo: implement this java.lang.Number abstract method*/ return (long)doubleValue();

}

@Override

public int compareTo(NewRational o) {

/**@todo: Implement this java.lang.Comparable method*/ if ((this.subtract((NewRational)o)).getNumerator() > 0) return 1;

else if ((this.subtract((NewRational)o)).getNumerator() < 0) return -1; else

return 0; } } 15

import java.math.*;

public class Exercise13_15 {

public static void main(String[] args) {

// Create and initialize two rational numbers r1 and r2.

Rational r1 = new Rational(new BigInteger(\"4\"), new BigInteger(\"2\")); Rational r2 = new Rational(new BigInteger(\"2\"), new BigInteger(\"3\"));

// Display results

System.out.println(r1 + \" + \" + r2 + \" = \" + r1.add(r2)); System.out.println(r1 + \" - \" + r2 + \" = \" + r1.subtract(r2)); System.out.println(r1 + \" * \" + r2 + \" = \" + r1.multiply(r2)); System.out.println(r1 + \" / \" + r2 + \" = \" + r1.divide(r2)); System.out.println(r2 + \" is \" + r2.doubleValue()); }

static class Rational extends Number implements Comparable { // Data fields for numerator and denominator private BigInteger numerator = BigInteger.ZERO; private BigInteger denominator = BigInteger.ONE;

/** Construct a rational with default properties */ public Rational() {

this(BigInteger.ZERO, BigInteger.ONE); }

/** Construct a rational with specified numerator and denominator */ public Rational(BigInteger numerator, BigInteger denominator) {

BigInteger gcd = gcd(numerator, denominator);

if (denominator.compareTo(BigInteger.ZERO) < 0)

this.numerator = numerator.multiply(new BigInteger(\"-1\")).divide(gcd); else

this.numerator = numerator.divide(gcd);

this.denominator = denominator.abs().divide(gcd); }

/** Find GCD of two numbers */

private static BigInteger gcd(BigInteger n, BigInteger d) { BigInteger n1 = n.abs(); BigInteger n2 = d.abs();

BigInteger gcd = BigInteger.ONE;

for (BigInteger k = BigInteger.ONE;

k.compareTo(n1) <= 0 && k.compareTo(n2) <= 0; k = k.add(BigInteger.ONE)) {

if (n1.remainder(k).equals(BigInteger.ZERO) && n2.remainder(k).equals(BigInteger.ZERO)) gcd = k; }

return gcd; }

/** Return numerator */

public BigInteger getNumerator() { return numerator; }

/** Return denominator */

public BigInteger getDenominator() { return denominator; }

/** Add a rational number to this rational */ public Rational add(Rational secondRational) {

BigInteger n = numerator.multiply(secondRational.getDenominator()).add( denominator.multiply(secondRational.getNumerator()));

BigInteger d = denominator.multiply(secondRational.getDenominator()); return new Rational(n, d); }

/** Subtract a rational number from this rational */ public Rational subtract(Rational secondRational) {

BigInteger n = numerator.multiply(secondRational.getDenominator()).subtract( denominator.multiply(secondRational.getNumerator()));

BigInteger d = denominator.multiply(secondRational.getDenominator()); return new Rational(n, d); }

/** Multiply a rational number to this rational */ public Rational multiply(Rational secondRational) {

BigInteger n = numerator.multiply(secondRational.getNumerator()); BigInteger d = denominator.multiply(secondRational.getDenominator()); return new Rational(n, d); }

/** Divide a rational number from this rational */ public Rational divide(Rational secondRational) {

BigInteger n = numerator.multiply(secondRational.getDenominator()); BigInteger d = denominator.multiply(secondRational.numerator); return new Rational(n, d); }

@Override

public String toString() {

if (denominator.equals(BigInteger.ONE)) return numerator + \"\"; else

return numerator + \"/\" + denominator; }

@Override /** Override the equals method in the Object class */ public boolean equals(Object parm1) {

if ((this.subtract((Rational)(parm1))).getNumerator().equals(BigInteger.ONE)) return true; else

return false; }

@Override /** Override the hashCode method in the Object class */ public int hashCode() {

return new Double(this.doubleValue()).hashCode(); }

@Override /** Override the abstract intValue method in java.lang.Number */

public int intValue() {

return (int)doubleValue(); }

@Override /** Override the abstract floatValue method in java.lang.Number */ public float floatValue() {

return (float)doubleValue(); }

@Override /** Override the doubleValue method in java.lang.Number */ public double doubleValue() {

return numerator.doubleValue() / denominator.doubleValue(); }

@Override /** Override the abstract longValue method in java.lang.Number */ public long longValue() {

return (long)doubleValue(); }

@Override

public int compareTo(Rational o) {

if ((this.subtract((Rational)o)).getNumerator().compareTo(BigInteger.ZERO) > 0) return 1;

else if ((this.subtract((Rational)o)).getNumerator().compareTo(BigInteger.ZERO) < 0) return -1; else

return 0; } } } 16

public class Exercise13_16 {

public static void main(String[] args) { Rational result = new Rational(0, 1);

if (args.length != 1) { System.out.println(

\"Usage: java Exercise13_16 \\\"operand1 operator operand2\\\"\"); System.exit(1); }

String[] tokens = args[0].split(\" \");

switch (tokens[1].charAt(0)) {

case '+': result = getRational(tokens[0]).add(getRational(tokens[2])); break;

case '-': result = getRational(tokens[0]).subtract(getRational(tokens[2])); break;

case '*': result = getRational(tokens[0]).multiply(getRational(tokens[2])); break;

case '/': result = getRational(tokens[0]).divide(getRational(tokens[2])); }

System.out.println(tokens[0] + \" \" + tokens[1] + \" \" + tokens[2] + \" = \" + result); }

static Rational getRational(String s) { String[] st = s.split(\"/\");

int numer = Integer.parseInt(st[0]); int denom = Integer.parseInt(st[1]); return new Rational(numer, denom); } }

/* Alternatively, you can use StringTokenizer. See Supplement III.AA on StringTokenizer as alternative

import java.util.StringTokenizer;

public class Exercise15_18 {

public static void main(String[] args) { Rational result = new Rational(0, 1);

if (args.length != 3) { System.out.println(

\"Usage: java Exercise15_22 operand1 operator operand2\"); System.exit(0); }

switch (tokens[1].charAt(0)) {

case '+': result = getRational(tokens[0]).add(getRational(tokens[2])); break;

case '-': result = getRational(tokens[0]).subtract(getRational(tokens[2])); break;

case '*': result = getRational(tokens[0]).multiply(getRational(tokens[2])); break;

case '/': result = getRational(tokens[0]).divide(getRational(tokens[2])); }

System.out.println(tokens[0] + \" \" + tokens[1] + \" \" + tokens[2] + \" = \" + result); }

static Rational getRational(String s) {

StringTokenizer st = new StringTokenizer(s, \"/\"); int numer = new Integer(st.nextToken()).intValue(); int denom = new Integer(st.nextToken()).intValue(); return new Rational(numer, denom); } } */ 17

import java.util.Scanner;

public class Exercise13_17 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print(\"Enter the first complex number: \"); double a = input.nextDouble(); double b = input.nextDouble(); Complex c1 = new Complex(a, b);

System.out.print(\"Enter the second complex number: \"); double c = input.nextDouble(); double d = input.nextDouble(); Complex c2 = new Complex(c, d);

System.out.println(\"(\" + c1 + \")\" + \" + \" + \"(\" + c2 + \")\" + \" = \" + c1.add(c2)); System.out.println(\"(\" + c1 + \")\" + \" - \" + \"(\" + c2 + \")\" + \" = \" + c1.subtract(c2)); System.out.println(\"(\" + c1 + \")\" + \" * \" + \"(\" + c2 + \")\" + \" = \" + c1.multiply(c2)); System.out.println(\"(\" + c1 + \")\" + \" / \" + \"(\" + c2 + \")\" + \" = \" + c1.divide(c2)); System.out.println(\"|\" + c1 + \"| = \" + c1.abs());

Complex c3 = (Complex)c1.clone(); System.out.println(c1 == c3);

System.out.println(c3.getRealPart());

System.out.println(c3.getImaginaryPart()); } }

class Complex implements Cloneable { private double a = 0, b = 0;

public Complex() { }

Complex(double a, double b) { this.a = a; this.b = b; }

public Complex(double a) { this.a = a; }

public double getA() { return a; }

public double getB() { return b; }

public Complex add(Complex secondComplex) { double newA = a + secondComplex.getA(); double newB = b + secondComplex.getB(); return new Complex(newA, newB); }

public Complex subtract(Complex secondComplex) { double newA = a - secondComplex.getA(); double newB = b - secondComplex.getB(); return new Complex(newA, newB); }

public Complex multiply(Complex secondComplex) {

double newA = a * secondComplex.getA() - b * secondComplex.getB(); double newB = b * secondComplex.getA() + a * secondComplex.getB(); return new Complex(newA, newB); }

public Complex divide(Complex secondComplex) {

double newA = (a * secondComplex.getA() + b * secondComplex.getB())

/ (Math.pow(secondComplex.getA(), 2.0) + Math.pow(secondComplex.getB(), 2.0));

double newB = (b * secondComplex.getA() - a * secondComplex.getB())

/ (Math.pow(secondComplex.getA(), 2.0) + Math.pow(secondComplex.getB(), 2.0));

return new Complex(newA, newB); }

public double abs() {

return Math.sqrt(a * a + b * b); }

@Override

public String toString() { if (b != 0)

return a + \" + \" + b + \"i\"; return a + \"\"; }

public double getRealPart() { return a; }

public double getImaginaryPart() { return b; }

@Override /** Implement the clone method in the Object class */ public Object clone() { // Implement it try {

return super.clone(); // Automatically perform a shallow copy }

catch (CloneNotSupportedException ex) { return null; } } } 18

public class Exercise13_18 {

public static void main(String[] args) { final int N = 100;

Rational sum = new Rational(); for (int i = 1; i <= N; i++)

sum = sum.add(new Rational(i - 1, i));

System.out.println(\"The sum of the first series is \" + sum + \" = \" + sum.doubleValue()); } } 19

import java.math.BigInteger; import java.util.Scanner;

public class Exercise13_19 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in); System.out.print(\"Enter a decimal: \"); String decimal = input.nextLine();

System.out.println(\"The fraction number is \" + getFraction(decimal)); }

private static Rational getFraction(String decimal) { String[] items = decimal.split(\"[.]\");

if (items.length == 1) {

return new Rational(new BigInteger(items[0]), BigInteger.ONE); } else {

Rational r = new Rational(new BigInteger(items[0] getDenominator(items[1].length())); return r; } }

private static BigInteger getDenominator(int size) { BigInteger result = BigInteger.ONE;

for (int i = 0; i < size; i++)

result = result.multiply(new BigInteger(\"10\"));

return result; }

static class Rational extends Number implements Comparable { // Data fields for numerator and denominator private BigInteger numerator = BigInteger.ZERO; private BigInteger denominator = BigInteger.ONE;

+ items[1]),

/** Construct a rational with default properties */ public Rational() {

this(BigInteger.ZERO, BigInteger.ONE); }

/** Construct a rational with specified numerator and denominator */ public Rational(BigInteger numerator, BigInteger denominator) { BigInteger gcd = gcd(numerator, denominator);

if (denominator.compareTo(BigInteger.ZERO) < 0)

this.numerator = numerator.multiply(new BigInteger(\"-1\")).divide(gcd); else

this.numerator = numerator.divide(gcd);

this.denominator = denominator.abs().divide(gcd); }

/** Find GCD of two numbers */

private static BigInteger gcd(BigInteger n, BigInteger d) { BigInteger n1 = n.abs(); BigInteger n2 = d.abs();

BigInteger gcd = BigInteger.ONE;

for (BigInteger k = BigInteger.ONE;

k.compareTo(n1) <= 0 && k.compareTo(n2) <= 0; k = k.add(BigInteger.ONE)) {

if (n1.remainder(k).equals(BigInteger.ZERO) && n2.remainder(k).equals(BigInteger.ZERO)) gcd = k; }

return gcd; }

/** Return numerator */

public BigInteger getNumerator() { return numerator; }

/** Return denominator */

public BigInteger getDenominator() { return denominator; }

/** Add a rational number to this rational */ public Rational add(Rational secondRational) {

BigInteger n = numerator.multiply(secondRational.getDenominator()).add( denominator.multiply(secondRational.getNumerator()));

BigInteger d = denominator.multiply(secondRational.getDenominator()); return new Rational(n, d); }

/** Subtract a rational number from this rational */ public Rational subtract(Rational secondRational) {

BigInteger n = numerator.multiply(secondRational.getDenominator()).subtract( denominator.multiply(secondRational.getNumerator()));

BigInteger d = denominator.multiply(secondRational.getDenominator()); return new Rational(n, d); }

/** Multiply a rational number to this rational */ public Rational multiply(Rational secondRational) {

BigInteger n = numerator.multiply(secondRational.getNumerator()); BigInteger d = denominator.multiply(secondRational.getDenominator()); return new Rational(n, d); }

/** Divide a rational number from this rational */ public Rational divide(Rational secondRational) {

BigInteger n = numerator.multiply(secondRational.getDenominator()); BigInteger d = denominator.multiply(secondRational.numerator); return new Rational(n, d); }

@Override

public String toString() {

if (denominator.equals(BigInteger.ONE)) return numerator + \"\"; else

return numerator + \"/\" + denominator; }

@Override /** Override the equals method in the Object class */ public boolean equals(Object parm1) {

if ((this.subtract((Rational)(parm1))).getNumerator().equals(BigInteger.ONE)) return true; else

return false;

}

@Override /** Override the hashCode method in the Object class */ public int hashCode() {

return new Double(this.doubleValue()).hashCode(); }

@Override /** Override the abstract intValue method in java.lang.Number */ public int intValue() {

return (int)doubleValue(); }

@Override /** Override the abstract floatValue method in java.lang.Number */ public float floatValue() {

return (float)doubleValue(); }

@Override /** Override the doubleValue method in java.lang.Number */ public double doubleValue() {

return numerator.doubleValue() / denominator.doubleValue(); }

@Override /** Override the abstract longValue method in java.lang.Number */ public long longValue() {

return (long)doubleValue(); }

@Override

public int compareTo(Rational o) {

if ((this.subtract((Rational)o)).getNumerator().compareTo(BigInteger.ZERO) > 0) return 1;

else if ((this.subtract((Rational)o)).getNumerator().compareTo(BigInteger.ZERO) < 0) return -1; else

return 0; } } } 20

import java.util.Scanner;

public class Exercise13_20 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print(\"Enter a, b, c: \"); double a = input.nextDouble(); double b = input.nextDouble(); double c = input.nextDouble();

double discriminant = b * b - 4 * a * c;

if (discriminant < 0) {

Complex r1 = new Complex(-b / (2 * a), Math.pow(-discriminant, 0.5) / (2 * a)); Complex r2 = new Complex(-b / (2 * a), -Math.pow(-discriminant, 0.5) / (2 * a)); System.out.println(\"The roots are \" + r1 + \" and \" + r2); }

else if (discriminant == 0) { double r1 = -b / (2 * a);

System.out.println(\"The root is \" + r1); }

else { // (discriminant > 0)

double r1 = (-b + Math.pow(discriminant, 0.5)) / (2 * a); double r2 = (-b - Math.pow(discriminant, 0.5)) / (2 * a); System.out.println(\"The roots are \" + r1 + \" and \" + r2); } } } 21

import java.util.Scanner;

public class Exercise13_21 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print(\"Enter a, b, c: \"); int a = input.nextInt(); int b = input.nextInt(); int c = input.nextInt();

Rational h = new Rational(-b, 2 * a);

Rational k = new Rational(4 * a * c - b * b, 4 * a);

System.out.print(\"h is \" + h + \" \" + \"k is \" + k); } }

因篇幅问题不能全部显示,请点此查看更多更全内容

Top