java语言程序设计基础篇第十版第十三章练习答案
- 格式:doc
- 大小:29.57 KB
- 文档页数:34
java语言程序设计基础篇第十版第十三章练习答案————————————————————————————————作者:————————————————————————————————日期: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;}@Overridepublic String toString() {// Implement it to return the three sidesreturn "TriangleNew: side1 = " + side1 + " side2 = " + side2 +" side3 = " + side3;}}02import java.util.ArrayList;public class Exercise13_02 {public static void main(String[] args) {ArrayList<Number> list = new ArrayList<Number>();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<Number> 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);}}}03import java.util.ArrayList;public class Exercise13_03 {public static void main(String[] args) {ArrayList<Number> list = new ArrayList<Number>();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<Number> 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);}}}}04import 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 yearyear = 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 yearmonth = Integer.parseInt(args[0]);calendar.set(Calendar.MONTH, month-1);}//set date to the first day in a monthcalendar.set(Calendar.DATE, 1);//print calendar for the monthprintMonth(year, month);}static void printMonth(int year, int month) {//get start day of the week for the first date in the monthint startDay = getStartDay();//get number of days in the monthint numOfDaysInMonth = calendar.daysInMonth();//print headingsprintMonthTitle(year, month);//print bodyprintMonthBody(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 monthint 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);elseSystem.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()+", "+year);System.out.println("-----------------------------");System.out.println(" Sun Mon Tue Wed Thu Fri Sat");}}05public class Exercise13_05 {// Main methodpublic static void main(String[] args) {// Create two comparable circlesCircle1 circle1 = new Circle1(5);Circle1 circle2 = new Circle1(4);// Display the max circleCircle1 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<GeometricObject1> { protected String color;protected double weight;// Default constructprotected GeometricObject1() {color = "white";weight = 1.0;}// Construct a geometric objectprotected GeometricObject1(String color, double weight) {this.color = color;this.weight = weight;// Getter method for colorpublic String getColor() {return color;}// Setter method for colorpublic void setColor(String color) {this.color = color;}// Getter method for weightpublic double getWeight() {return weight;}// Setter method for weightpublic void setWeight(double weight) {this.weight = weight;}// Abstract methodpublic abstract double getArea();// Abstract methodpublic abstract double getPerimeter();public int compareTo(GeometricObject1 o) {if (getArea() < o.getArea())return -1;else if (getArea() == o.getArea())return 0;elsereturn 1;}public static GeometricObject1 max(GeometricObject1 o1, GeometricObject1 o2) { if (pareTo(o2) > 0)return o1;elsereturn o2;}}// Circle.java: The circle class that extends GeometricObjectclass Circle1 extends GeometricObject1 {protected double radius;// Default constructorpublic Circle1() {this(1.0, "white", 1.0);}// Construct circle with specified radiuspublic Circle1(double radius) {super("white", 1.0);this.radius = radius;}// Construct a circle with specified radius, weight, and colorpublic Circle1(double radius, String color, double weight) {super(color, weight);this.radius = radius;}// Getter method for radiuspublic double getRadius() {return radius;}// Setter method for radiuspublic 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 classpublic boolean equals(Circle1 circle) {return this.radius == circle.getRadius();}@Overridepublic String toString() {return "[Circle] radius = " + radius;}@Overridepublic int compareTo(GeometricObject1 o) {if (getRadius() > ((Circle1) o).getRadius())return 1;else if (getRadius() < ((Circle1) o).getRadius())return -1;elsereturn 0;}}06public class Exercise13_06 {// Main methodpublic static void main(String[] args) {// Create two comarable rectanglesComparableCircle circle1 = new ComparableCircle(5);ComparableCircle circle2 = new ComparableCircle(15);// Display the max rectComparableCircle 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<ComparableCircle> { /** Construct a ComparableRectangle with specified properties */public ComparableCircle(double radius) {super(radius);}@Overridepublic int compareTo(ComparableCircle o) {if (getRadius() > o.getRadius())return 1;else if (getRadius() < o.getRadius())return -1;elsereturn 0;}}//Max.java: Find a maximum objectclass Max {/** Return the maximum of two objects */public static ComparableCircle max(ComparableCircle o1, ComparableCircle o2) {if (pareTo(o2) > 0)return o1;elsereturn o2;}}07public 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;}@Overridepublic void howToColor() {System.out.println("Color all four sides");}@Overridepublic double getArea() {return side * side;}@Overridepublic double getPerimeter() {return 4 * side;}}08import 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<Object> list = new ArrayList<Object>();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<Object>) this.list.clone();return c;} catch (CloneNotSupportedException ex) {return null;}}}09public 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(pareTo(obj2)); }}// Circle.java: The circle class that extends GeometricObjectclass Circle13_09 extends GeometricObject implements Comparable<Circle13_09> { 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;}@Overridepublic String toString() {return "[Circle] radius = " + radius;}@Overridepublic int compareTo(Circle13_09 obj) {if (this.getArea() > obj.getArea())return 1;else if (this.getArea() < obj.getArea())return -1;elsereturn 0;}public boolean equals(Object obj) {return this.radius == ((Circle13_09)obj).radius;}}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(pareTo(obj2));}}// Rectangle.java: The Rectangle class that extends GeometricObjectclass Rectangle13_10 extends GeometricObject implements Comparable<Rectangle13_10> { 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);}@Overridepublic String toString() {return "[Rectangle] width = " + width +" and height = " + height;}@Overridepublic int compareTo(Rectangle13_10 obj) {if (this.getArea() > obj.getArea())return 1;else if (this.getArea() < obj.getArea())return -1;elsereturn 0;}public boolean equals(Object obj) {return this.getArea() == ((Rectangle13_10)obj).getArea();}}11public 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 " + pareTo(a2)); }}class Octagon extends GeometricObjectimplements Comparable<Octagon>, Cloneable {private double side;/** Construct a Octagon with the default side */public Octagon () {// Implement itthis.side = 1;}/** Construct a Octagon with the specified side */public Octagon (double side) {// Implement itthis.side = side;}@Override /** Implement the abstract method getArea in GeometricObject */public double getArea() {// Implement itreturn (2 + 4 / Math.sqrt(2)) * side * side;}@Override /** Implement the abstract method getPerimeter in GeometricObject */public double getPerimeter() {// Implement itreturn 8 * side;}@Overridepublic int compareTo(Octagon obj) {if (this.side > obj.side)return 1;else if (this.side == obj.side)return 0;elsereturn -1;}@Override /** Implement the clone method inthe Object class */public Object clone() {// Octagon o = new Octagon();// o.side = this.side;// return o;//// Implement ittry {return super.clone(); // Automatically perform a shallow copy }catch (CloneNotSupportedException ex) {return null;}}}12public 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());}@Overridepublic String toString() {return "[Rectangle] width = " + width +" and height = " + height;}}13public 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;}}}14class NewRational extends Number implements Comparable<NewRational> { // Data fields for numerator and denominatorprivate 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);}@Overridepublic String toString() {if (r[1] == 1)return r[0] + "";elsereturn r[0] + "/" + r[1];}/**Override the equals method*/public boolean equals(Object parm1) {/**@todo: Override this ng.Object method*/if ((this.subtract((NewRational)(parm1))).getNumerator() == 0)return true;elsereturn false;}/**Override the intValue method*/public int intValue() {/**@todo: implement this ng.Number abstract method*/ return (int)doubleValue();}/**Override the floatValue method*/public float floatValue() {/**@todo: implement this ng.Number abstract method*/ return (float)doubleValue();}/**Override the doubleValue method*/public double doubleValue() {/**@todo: implement this ng.Number abstract method*/ return r[0]*1.0/r[1];}/**Override the longValue method*/public long longValue() {/**@todo: implement this ng.Number abstract method*/ return (long)doubleValue();}@Overridepublic int compareTo(NewRational o) {/**@todo: Implement this parable method*/if ((this.subtract((NewRational)o)).getNumerator() > 0)return 1;else if ((this.subtract((NewRational)o)).getNumerator() < 0)return -1;elsereturn 0;}}15import 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 resultsSystem.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<Rational> { // Data fields for numerator and denominatorprivate 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 (pareTo(BigInteger.ZERO) < 0)this.numerator = numerator.multiply(new BigInteger("-1")).divide(gcd); elsethis.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;pareTo(n1) <= 0 && pareTo(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);}@Overridepublic String toString() {if (denominator.equals(BigInteger.ONE))return numerator + "";elsereturn 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;elsereturn 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 ng.Number */public int intValue() {return (int)doubleValue();}@Override /** Override the abstract floatValue method in ng.Number */public float floatValue() {return (float)doubleValue();}@Override /** Override the doubleValue method in ng.Number */public double doubleValue() {return numerator.doubleValue() / denominator.doubleValue();}@Override /** Override the abstract longValue method in ng.Number */public long longValue() {return (long)doubleValue();}@Overridepublic 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;elsereturn 0;}}}16public 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 alternativeimport 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]));}。
第一章1.1public class Test{public static void main(String[]args){System.out.println("Welcome to Java!"); System.out.println("Welcome to Computer Science!");System.out.println("Progr amming is fun.");}}1.2public class Test{public static void main(String[]args){for(int i=0;i<=4;i++){System.out.println("Welcome to Java!");}}}1.3public class Test{public static void main(String[]args){System.out.println("]");System.out.printl n("]");System.out.println("]]");System.out.println("]]");}}public class Test{public static void main(String[]args){System.out.println("A"); System.out.println("A A");System.out.println("AAAAA");System.out.println("A A");}}public class Test{public static void main(String[]args){System.out.println("V V");System.out.println("V V");System.out.println("V V");System.out.println(" V");}}1.4public class Test{public static void main(String[]args){System.out.println("a a^2a^3");System.out.println("111");System.out.println("248");System.out.println("3 927");System.out.println("41664");}}1.5public class Test{public static void main(String[]args){System.out.println((9.5*4.5-2.5*3)/(45.5-3.5) );}}1.6public class Test{public static void main(String[]args){int i=1,sum=0;for(;i<=9;i++)sum+ =i;System.out.println(sum);}1.7public class Test{public static void main(String[]args){System.out.println(4*(1.0-1.0/3+1.0/5-1.0/7+1.0/9-1.0/11));System.out.println(4*(1.0-1.0/3+1.0/5-1.0/7+1.0/9-1.0/11+1.0/13));}}1.8public class Test{public static void main(String[]args){final double PI=3.14; double radius=5.5;System.out.println(2*radius*PI);System.out.println(PI*radius*radius);}}1.9public class Test{public static void main(String[]args){System.out.println(7.9*4.5);System.out.p rintln(2*(7.9+4.5));}}1.10public class Test{public static void main(String[]args){double S=14/1.6;double T=45*60+30;double speed=S/T;System.out.println(speed);}1.11public class Test{public static void main(String[]args){int BN=312032486; //original person numbers double EveryYS,EveryYBP,EveryYDP,EveryYMP;EveryY S=365*24*60*60;EveryYBP=EveryYS/7;EveryYDP=EveryYS/13;Every YMP=EveryYS/45;int FirstYP,SecondYP,ThirdYP,FourthYP,FivthYP;FirstYP=(int)(BN+EveryYBP+EveryYMP-EveryYDP);SecondYP=(int)(FirstYP +EveryYBP+EveryYMP-EveryYDP);ThirdYP=(int)(SecondYP+EveryYBP+Ev eryYMP-EveryYDP);FourthYP=(int)(ThirdYP+EveryYBP+EveryYMP-EveryYD P);FivthYP=(int)(FourthYP+EveryYBP+EveryYMP-EveryYDP);System.out.pri ntln(FirstYP);System.out.println(SecondYP);System.out.println(ThirdYP);Syste m.out.println(FourthYP);System.out.println(FivthYP);}}1.12public class Test{public static void main(String[]args){double S=24*1.6; double T=(1*60+40)*60+35;double speed=S/T;System.out.println(sp eed);}}1.13import java.util.Scanner;public class Test{public static void main(String[]args){Scanner input=new Scan ner(System.in);System.out.println("input a,b,c,d,e,f value please:");double a=input.nextDouble();double b=input.nextDouble();double c=input.nextDouble();double d=input. nextDouble();double e=input.nextDouble();第二章package cn.Testcx;import java.util.Scanner;public class lesson2{public static void main(String[]args){@SuppressWarnings("resource")Scanner in put=new Scanner(System.in);System.out.print("请输入一个摄氏温度:");double Celsius=input.nextDouble();double Fahrenheit=(9.0/5)*Celsius+3 2;System.out.println("摄氏温度:"+Celsius+"度"+"转换成华氏温度为:"+Fahrenheit+"度");System.out.print("请输入圆柱的半径和高:");double radius=input.nextDouble();int higth=input.nextInt();double are as=radius*radius*Math.PI;double volume=areas*higth;System.out.println("圆柱体的面积为:"+areas);System.out.println("圆柱体的体积为:"+volume);System.out.print("输入英尺数:");double feet=input.nextDouble();double meters=feet*0.305;System.out.print ln(feet+"英尺转换成米:"+meters);System.out.print("输入一个磅数:");double pounds=input.nextDouble();double kilograms=pounds*0.454;Syste m.out.println(pounds+"磅转换成千克为:"+kilograms);System.out.println("输入分钟数:");long minutes=input.nextInt();long years=minutes/(24*60*365);long days=(minutes%(24*60*365))/(24*60);System.out.println(minutes+"分钟"+"有"+years+"年和"+days+"天");long totalCurrentTimeMillis=System.currentTimeMillis();long totalSeconds=t otalCurrentTimeMillis/1000;long currentSeconds=totalSeconds%60;long totalM inutes=totalSeconds/60;long currentMinutes=(totalSeconds%(60*60))/60;long currenthours=(totalMinutes/60)%24;System.out.print("输入时区偏移量:");byte zoneOffset=input.nextByte();long currentHour=(currenthours+(zoneOf fset*1))%24;System.out.println("当期时区的时间为:"+currentHour+"时"+currentMinutes+"分"+currentSeconds+"秒");System.out.print("请输入v0,v1,t:");double v0=input.nextDouble();double v1=input.nextDouble();doublet=input.nextDouble();float a=(float)((v1-v0)/t);System.out.println("平均加速度a="+a);System.out.println("输入水的重量、初始温度、最终温度:");double water=input.nextDouble();double initialTemperature=input.nextDou ble();double finalTemperature=input.nextDouble();double Q=water*(finalTemp erature-initialTemperature)*4184;System.out.println("所需热量为:"+Q);System.out.print("输入年数:");int numbers=input.nextInt();long oneYearsSecond=365*24*60*60;Longpop ulation=(long)((312032486+((oneYearsSecond/7.0)+(oneYearsSecond/45.0)-(oneYearsSecond/13.0))*numbers));System.out.println("第"+numbers+"年后人口总数为:"+population);System.out.print("输入速度单位m/s和加速度a单位m/s2:");double v=input.nextDouble();double a1=input.nextDouble();double l engthOfAirplane=(Math.pow(v,2))/(2*a1);System.out.println("最短长度为:"+lengthOfAirplane);System.out.print("输入存入的钱:");double money=input.nextInt();double monthRate=5.0/1200;for(int i=1;i<7; i++){double total=money*(Math.pow(1+monthRate,i));System.out.println("第"+i+"个月的钱为:"+total);//告诉我书上的银行在哪里,我要去存钱,半年本金直接翻6倍、、、}System.out.print("用户请输入身高(英寸)、体重(磅):");double height=input.nextDouble();double weight=input.nextDouble(); double BMI=(weight*0.45359237)/(Math.pow((height*0.0254),2));System.out.println("BMI的值为"+BMI);System.out.print("输入x1和y1:");System.out.print("输入x2和y2:");double x1=input.nextDouble();double y1=input.nextDouble();double x2 =input.nextDouble();double y2=input.nextDouble();double point1=Math.pow((x2-x1),2);double point2=Math.pow((y2-y1),2);double distance=Math.pow((point1+point2),(1.0/2));//也可以Math.pow((point1+point2),0.5)System.out.println("两点间的距离为:"+distance);System.out.print("输入六边形的边长:");double side=input.nextDouble();double area=(3*(Math.pow(3,0.5))*(Math.p ow(side,2)))/2;System.out.println("六边形的面积为:"+area);}}。
《Java语言程序设计(基础篇)》(第10版梁勇著)第九章练习题答案9.1public class Exercise09_01 {public static void main(String[] args) {MyRectangle myRectangle = new MyRectangle(4, 40);System.out.println("The area of a rectangle with width " +myRectangle.width + " and height " +myRectangle.height + " is " +myRectangle.getArea());System.out.println("The perimeter of a rectangle is " +myRectangle.getPerimeter());MyRectangle yourRectangle = new MyRectangle(3.5, 35.9);System.out.println("The area of a rectangle with width " +yourRectangle.width + " and height " +yourRectangle.height + " is " +yourRectangle.getArea());System.out.println("The perimeter of a rectangle is " +yourRectangle.getPerimeter());}}class MyRectangle {// Data membersdouble width = 1, height = 1;// Constructorpublic MyRectangle() {}// Constructorpublic MyRectangle(double newWidth, double newHeight) {width = newWidth;height = newHeight;}public double getArea() {return width * height;}public double getPerimeter() {return 2 * (width + height);}}9.2public class Exercise09_02 {public static void main(String[] args) {Stock stock = new Stock("SUNW", "Sun MicroSystems Inc."); stock.setPreviousClosingPrice(100);// Set current pricestock.setCurrentPrice(90);// Display stock infoSystem.out.println("Previous Closing Price: " +stock.getPreviousClosingPrice());System.out.println("Current Price: " +stock.getCurrentPrice());System.out.println("Price Change: " +stock.getChangePercent() * 100 + "%");}}class Stock {String symbol;String name;double previousClosingPrice;double currentPrice;public Stock() {}public Stock(String newSymbol, String newName) {symbol = newSymbol;name = newName;}public double getChangePercent() {return (currentPrice - previousClosingPrice) /previousClosingPrice;}public double getPreviousClosingPrice() {return previousClosingPrice;}public double getCurrentPrice() {return currentPrice;}public void setCurrentPrice(double newCurrentPrice) {currentPrice = newCurrentPrice;}public void setPreviousClosingPrice(double newPreviousClosingPrice) { previousClosingPrice = newPreviousClosingPrice;}}9.3public class Exercise09_03 {public static void main(String[] args) {Date date = new Date();int count = 1;long time = 10000;while (count <= 8) {date.setTime(time);System.out.println(date.toString());count++;time *= 10;}}}9.4public class Exercise09_04 {public static void main(String[] args) {Random random = new Random(1000);for (int i = 0; i < 50; i++)System.out.print(random.nextInt(100) + " ");}9.5public class Exercise09_05 {public static void main(String[] args) {GregorianCalendar calendar = new GregorianCalendar();System.out.println("Year is " + calendar.get(GregorianCalendar.YEAR)); System.out.println("Month is " + calendar.get(GregorianCalendar.MONTH)); System.out.println("Date is " + calendar.get(GregorianCalendar.DATE));calendar.setTimeInMillis(1234567898765L);System.out.println("Year is " + calendar.get(GregorianCalendar.YEAR)); System.out.println("Month is " + calendar.get(GregorianCalendar.MONTH)); System.out.println("Date is " + calendar.get(GregorianCalendar.DATE)); }}9.6public class Exercise09_06 {static String output = "";/** Main method */public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter yearSystem.out.print("Enter full year (i.e. 2001): ");int year = input.nextInt();// Prompt the user to enter monthSystem.out.print("Enter month in number between 1 and 12: ");int month = input.nextInt();// Print calendar for the month of the yearprintMonth(year, month);System.out.println(output);}/** Print the calendar for a month in a year */static void printMonth(int year, int month) {// Get start day of the week for the first date in the monthint startDay = getStartDay(year, month);// Get number of days in the monthint numOfDaysInMonth = getNumOfDaysInMonth(year, month);// Print headingsprintMonthTitle(year, month);// Print bodyprintMonthBody(startDay, numOfDaysInMonth);}/** Get the start day of the first day in a month */static int getStartDay(int year, int month) {// Get total number of days since 1/1/1800int startDay1800 = 3;long totalNumOfDays = getTotalNumOfDays(year, month);// Return the start dayreturn (int)((totalNumOfDays + startDay1800) % 7);}/** Get the total number of days since Jan 1, 1800 */static long getTotalNumOfDays(int year, int month) {long total = 0;// Get the total days from 1800 to year -1for (int i = 1800; i < year; i++)if (isLeapYear(i))total = total + 366;elsetotal = total + 365;// Add days from Jan to the month prior to the calendar month for (int i = 1; i < month; i++)total = total + getNumOfDaysInMonth(year, i);return total;}/** Get the number of days in a month */static int getNumOfDaysInMonth(int year, int month) {if (month == 1 || month==3 || month == 5 || month == 7 ||month == 8 || month == 10 || month == 12)return 31;if (month == 4 || month == 6 || month == 9 || month == 11)return 30;if (month == 2)if (isLeapYear(year))return 29;elsereturn 28;return 0; // If month is incorrect.}/** Determine if it is a leap year */static boolean isLeapYear(int year) {if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) return true;return false;}/** Print month body */static void printMonthBody(int startDay, int numOfDaysInMonth) { // Pad space before the first day of the monthint i = 0;for (i = 0; i < startDay; i++)output += " ";for (i = 1; i <= numOfDaysInMonth; i++) {if (i < 10)output += " " + i;elseoutput += " " + i;if ((i + startDay) % 7 == 0)output += "\n";}output += "\n";}/** Print the month title, i.e. May, 1999 */static void printMonthTitle(int year, int month) {output += " " + getMonthName(month)+ ", " + year + "\n";output += "-----------------------------\n";output += " Sun Mon Tue Wed Thu Fri Sat\n";}/** Get the English name for the month */static String getMonthName(int month) {String monthName = null;switch (month) {case 1: monthName = "January"; break;case 2: monthName = "February"; break;case 3: monthName = "March"; break;case 4: monthName = "April"; break;case 5: monthName = "May"; break;case 6: monthName = "June"; break;case 7: monthName = "July"; break;case 8: monthName = "August"; break;case 9: monthName = "September"; break;case 10: monthName = "October"; break;case 11: monthName = "November"; break;case 12: monthName = "December";}return monthName;}}9.7public class Exercise09_07 {public static void main (String[] args) {Account account = new Account(1122, 20000);Account.setAnnualInterestRate(4.5);account.withdraw(2500);account.deposit(3000);System.out.println("Balance is " + account.getBalance()); System.out.println("Monthly interest is " +account.getMonthlyInterest());System.out.println("This account was created at " +account.getDateCreated());}}class Account {private int id;private double balance;private static double annualInterestRate;private java.util.Date dateCreated;public Account() {dateCreated = new java.util.Date();}public Account(int newId, double newBalance) {id = newId;balance = newBalance;dateCreated = new java.util.Date();}public int getId() {return this.id;}public double getBalance() {return balance;}public static double getAnnualInterestRate() {return annualInterestRate;}public void setId(int newId) {id = newId;}public void setBalance(double newBalance) {balance = newBalance;}public static void setAnnualInterestRate(double newAnnualInterestRate) { annualInterestRate = newAnnualInterestRate;}public double getMonthlyInterest() {return balance * (annualInterestRate / 1200);}public java.util.Date getDateCreated() { return dateCreated;}public void withdraw(double amount) {balance -= amount;}public void deposit(double amount) {balance += amount;}}9.8public class Exercise09_08 {public static void main(String[] args) { Fan1 fan1 = new Fan1();fan1.setSpeed(Fan1.FAST);fan1.setRadius(10);fan1.setColor("yellow");fan1.setOn(true);System.out.println(fan1.toString());Fan1 fan2 = new Fan1();fan2.setSpeed(Fan1.MEDIUM);fan2.setRadius(5);fan2.setColor("blue");fan2.setOn(false);System.out.println(fan2.toString()); }}class Fan1 {public static int SLOW = 1;public static int MEDIUM = 2;public static int FAST = 3;private int speed = SLOW;private boolean on = false;private double radius = 5;private String color = "white";public Fan1() {}public int getSpeed() {return speed;}public void setSpeed(int newSpeed) {speed = newSpeed;}public boolean isOn() {return on;}public void setOn(boolean trueOrFalse) {this.on = trueOrFalse;}public double getRadius() {return radius;}public void setRadius(double newRadius) { radius = newRadius;}public String getColor() {return color;}public void setColor(String newColor) {color = newColor;}@Overridepublic String toString() {return"speed " + speed + "\n"+ "color " + color + "\n"+ "radius " + radius + "\n"+ ((on) ? "fan is on" : " fan is off"); }}public class Exercise09_09 {public static void main(String[] args) {RegularPolygon polygon1 = new RegularPolygon();RegularPolygon polygon2 = new RegularPolygon(6, 4);RegularPolygon polygon3 = new RegularPolygon(10, 4, 5.6, 7.8);System.out.println("Polygon 1 perimeter: " +polygon1.getPerimeter());System.out.println("Polygon 1 area: " + polygon1.getArea());System.out.println("Polygon 2 perimeter: " +polygon2.getPerimeter());System.out.println("Polygon 2 area: " + polygon2.getArea());System.out.println("Polygon 3 perimeter: " +polygon3.getPerimeter());System.out.println("Polygon 3 area: " + polygon3.getArea());}}class RegularPolygon {private int n = 3;private double side = 1;private double x;private double y;public RegularPolygon() {}public RegularPolygon(int number, double newSide) {n = number;side = newSide;}public RegularPolygon(int number, double newSide, double newX, double newY) {n = number;side = newSide;x = newX;y = newY;}public int getN() {return n;}public void setN(int number) {n = number;}public double getSide() {return side;}public void setSide(double newSide) {side = newSide;}public double getX() {return x;}public void setX(double newX) {x = newX;}public double getY() {return y;}public void setY(double newY) {y = newY;}public double getPerimeter() {return n * side;}public double getArea() {return n * side * side / (Math.tan(Math.PI / n) * 4); }}9.10public class Exercise09_10 {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();QuadraticEquation equation = new QuadraticEquation(a, b, c);double discriminant = equation.getDiscriminant();if (discriminant < 0) {System.out.println("The equation has no roots");}else if (discriminant == 0){System.out.println("The root is " + equation.getRoot1());}else// (discriminant >= 0){System.out.println("The roots are " + equation.getRoot1()+ " and " + equation.getRoot2());}}}class QuadraticEquation {private double a;private double b;private double c;public QuadraticEquation(double newA, double newB, double newC) {a = newA;b = newB;c = newC;}double getA() {return a;}double getB() {return b;}double getC() {return c;}double getDiscriminant() {return b * b - 4 * a * c;}double getRoot1() {if (getDiscriminant() < 0)return 0;else {return (-b + getDiscriminant()) / (2 * a);}}double getRoot2() {if (getDiscriminant() < 0)return 0;else {return (-b - getDiscriminant()) / (2 * a);}}}9.11public class Exercise09_11 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a, b, c, d, e, f: ");double a = input.nextDouble();double b = input.nextDouble();double c = input.nextDouble();double d = input.nextDouble();double e = input.nextDouble();double f = input.nextDouble();LinearEquation equation = new LinearEquation(a, b, c, d, e, f);if (equation.isSolvable()) {System.out.println("x is " +equation.getX() + " and y is " + equation.getY());}else {System.out.println("The equation has no solution");}}}class LinearEquation {private double a;private double b;private double c;private double d;private double e;private double f;public LinearEquation(double newA, double newB, double newC, double newD, double newE, double newF) {a = newA;b = newB;c = newC;d = newD;e = newE;f = newF;}double getA() {return a;}double getB() {return b;}double getC() {return c;}double getD() {return d;}double getE() {return e;}double getF() {return f;}boolean isSolvable() {return a * d - b * c != 0;}double getX() {double x = (e * d - b * f) / (a * d - b * c);return x;}double getY() {double y = (a * f - e * c) / (a * d - b * c);return y;}}9.12public class Exercise09_12 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter the endpoints of the first line segment: ");double x1 = input.nextDouble();double y1 = input.nextDouble();double x2 = input.nextDouble();double y2 = input.nextDouble();System.out.print("Enter the endpoints of the second line segment: ");double x3 = input.nextDouble();double y3 = input.nextDouble();double x4 = input.nextDouble();double y4 = input.nextDouble();// Build a 2 by 2 linear equationdouble a = (y1 - y2);double b = (-x1 + x2);double c = (y3 - y4);double d = (-x3 + x4);double e = -y1 * (x1 - x2) + (y1 - y2) * x1;double f = -y3 * (x3 - x4) + (y3 - y4) * x3;LinearEquation equation = new LinearEquation(a, b, c, d, e, f);if (equation.isSolvable()) {System.out.println("The intersecting point is: (" +equation.getX() + ", " + equation.getY() + ")");}else {System.out.println("The two lines do not cross ");}}}9.13public class Exercise09_13 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter the number of rows and columns of the array: ");int numberOfRows = input.nextInt();int numberOfColumns = input.nextInt();double[][] a = new double[numberOfRows][numberOfColumns];System.out.println("Enter the array: ");for (int i = 0; i < a.length; i++)for (int j = 0; j < a[i].length; j++)a[i][j] = input.nextDouble();Location location = locateLargest(a);System.out.println("The location of the largest element is " + location.maxValue + " at ("+ location.row + ", " + location.column + ")");}public static Location locateLargest(double[][] a) {Location location = new Location();location.maxValue = a[0][0];for (int i = 0; i < a.length; i++)for (int j = 0; j < a[i].length; j++) {if (location.maxValue < a[i][j]) {location.maxValue = a[i][j];location.row = i;location.column = j;}}return location;}}class Location {int row, column;double maxValue;}9.14public class Exercise09_14 {public static void main(String[] args) {int size = 100000;double[] list = new double[size];for (int i = 0; i < list.length; i++) {list[i] = Math.random() * list.length;}StopWatch stopWatch = new StopWatch();selectionSort(list);stopWatch.stop();System.out.println("The sort time is " + stopWatch.getElapsedTime()); }/** The method for sorting the numbers */public static void selectionSort(double[] list) {for (int i = 0; i < list.length - 1; i++) {// Find the minimum in the list[i..list.length-1]double currentMin = list[i];int currentMinIndex = i;for (int j = i + 1; j < list.length; j++) {if (currentMin > list[j]) {currentMin = list[j];currentMinIndex = j;}}// Swap list[i] with list[currentMinIndex] if necessary;if (currentMinIndex != i) {list[currentMinIndex] = list[i];list[i] = currentMin;}}}}class StopWatch {private long startTime = System.currentTimeMillis(); private long endTime = startTime;public StopWatch() {}public void start() {startTime = System.currentTimeMillis();}public void stop() {endTime = System.currentTimeMillis();}public long getElapsedTime() {return endTime - startTime;}}。
j a v a语言程序设计基础篇第十版练习答案精编Document number:WTT-LKK-GBB-08921-EIGG-2298601import class Exercise14_01 extendsApplication {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}02import class Exercise14_02 extends Application {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}03import class Exercise14_03 extends Application {@Override One is to use the hint in the book.ArrayList<Integer> list = new ArrayList<>(); for (int i = 1; i <= 52; i++) {(i);}HBox pane = new HBox(5);;().add(new ImageView("image/card/" + (0) +".png"));().add(new ImageView("image/card/" + (1) +".png"));().add(new ImageView("image/card/" + (2) +".png"));Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}04import class Exercise14_04 extends Application {@Override dd(txt);}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}05import class Exercise14_05 extends Application {@Override dd(txt);}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}05import class Exercise14_05 extends Application {@Override dd(txt);}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}06import class Exercise14_06 extends Application {@Override dd(rectangle);}}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}07import class Exercise14_07 extends Application {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}08import class Exercise14_08 extends Application {@Override ng"), j, i);}}Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}09import class Exercise14_09 extends Application {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}class FanPane extends Pane {double radius = 50;public FanPane() {Circle circle = new Circle(60, 60, radius);;;getChildren().add(circle);Arc arc1 = new Arc(60, 60, 40, 40, 30, 35);; ddAll(arc1, arc2, arc3, arc4);}}10import class Exercise14_10 extends Application {@Override ddAll, ;Arc arc2 = new Arc(100, 140, 50, 20, 180, 180); ;;().addAll(ellipse, arc1, arc2,new Line(50, 40, 50, 140), new Line(150, 40, 150, 140));Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}11import class Exercise14_11 extends Application {@Override ddAll(circle, ellipse1, ellipse2,circle1, circle2, line1, line2, line3, arc);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}12import class Exercise14_12 extends Application {@Override ddAll(r1, text1, r2, text2, r3, text3, r4, text4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}13import class Exercise14_13 extends Application {@Override ddAll(arc1, text1, arc2, text2, arc3, text3, arc4, text4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}14import class Exercise14_14 extends Application {@Override ddAll(r1, r2, line1, line2, line3, line4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}15import class Exercise14_15 extends Application {@Override ddAll(polygon, text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16import class Exercise14_16 extends Application {@Override ind().divide(3));().bind());().bind().divide(3));;Line line2 = new Line(0, 0, 0, 0);().bind().multiply(2).divide(3));().bind());().bind().multiply(2).divide(3));;Line line3 = new Line(0, 0, 0, 0);().bind().divide(3));().bind().divide(3));().bind());;Line line4 = new Line(0, 0, 0, 0);().bind().multiply(2).divide(3));().bind().multiply(2).divide(3));().bind());;().addAll(line1, line2, line3, line4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}17import class Exercise14_17 extends Application {@Override ddAll(arc, line1, line2, line3, circle, line4, line5, line6, line7, line8);Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}18import class Exercise14_18 extends Application {@Override ddAll(polyline, line1, line2,line3, line4, line5, line6, text1, text2);Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}19import class Exercise14_19 extends Application {@Override ddAll(polyline1, polyline2, line1,line2,line3, line4, line5, line6, text1, text2,text3,text4, text5, text6, text7);Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}20import class Exercise14_20 extends Application {@Override dd(new Line(x1, y1, x2, y2));dd(new Line(x2, y2, (x2 + (arctan + set45) * arrlen)),((y2)) + (arctan + set45) * arrlen)));().add(new Line(x2, y2, (x2 + (arctan - set45) * arrlen)),((y2)) + (arctan - set45) * arrlen)));}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}21import class Exercise14_21 extends Application {@Override istance(x2, y2) + "");().addAll(circle1, circle2, line, text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}22import class Exercise14_22 extends Application {@Override ddAll(circle1, circle2, line, text1, text2);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}23import class Exercise14_23 extends Application {@Override ddAll(r1, r2, text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}24import class Exercise14_24 extends Application {@Override ddAll(polygon, new Circle(x5, y5, 10), text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}25import class Exercise14_25 extends Application {@Override ddAll(circle, polygon);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}26import class Exercise14_26 extends Application {@Override ddAll(clock1, clock2);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}27import class Exercise14_27 extends Application {@OverrideNot needed for running from the command line. */public static void main(String[] args) {launch(args);}}class DetailedClockPane extends Pane {private int hour;private int minute;private int second;lear();getChildren().addAll(circle, sLine, mLine, hLine);dd(new Line(xOuter, yOuter, xInner, yInner));}dd(text);}}}28import class Exercise14_28 extends Application {@OverrideNot needed for running from the command line.*/public static void main(String[] args) {launch(args);}}class ClockPaneWithBooleanProperties extends Pane { private int hour;private int minute;private int second;private boolean hourHandVisible = true;private boolean minuteHandVisible = true; private boolean secondHandVisible = true;public boolean isHourHandVisible() {return hourHandVisible;}public void setHourHandVisible(boolean hourHandVisible) {= hourHandVisible;paintClock();}public boolean isMinuteHandVisible() {return minuteHandVisible;}public void setMinuteHandVisible(boolean minuteHandVisible) {= minuteHandVisible;paintClock();}public boolean isSecondHandVisible() {return secondHandVisible;public void setSecondHandVisible(boolean secondHandVisible) {= secondHandVisible;paintClock();}lear();getChildren().addAll(circle, t1, t2, t3, t4);if (secondHandVisible) {getChildren().add(sLine);}if (minuteHandVisible) {getChildren().add(mLine);}if (hourHandVisible) {getChildren().add(hLine);}}}import class Exercise14_29 extends Application {final static double HGAP = 20;final static double VGAP = 20;final static double RADIUS = 5;final static double LENGTH_OF_SLOTS = 40;final static double LENGTH_OF_OPENNING = 15;final static double Y_FOR_FIRST_NAIL = 50;final static double NUMBER_OF_SLOTS = 9;final static double NUMBER_OF_ROWS =NUMBER_OF_SLOTS - 2;@Override dd(c);}}dd(new Line(x, y, x, y + LENGTH_OF_SLOTS)); }dd(new Line(centerX - (NUMBER_OF_ROWS - 1) * HGAP / 2 - HGAP,y + LENGTH_OF_SLOTS, centerX -(NUMBER_OF_ROWS - 1) * HGAP / 2 + NUMBER_OF_ROWS * HGAP,y + LENGTH_OF_SLOTS));dd(new Line(centerX + HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX - (NUMBER_OF_ROWS - 1) * HGAP / 2 + NUMBER_OF_ROWS * HGAP, y));().add(new Line(centerX - HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX - (NUMBER_OF_ROWS - 1) * HGAP / 2 - HGAP, y));dd(new Line(centerX - HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX - HGAP / 2, Y_FOR_FIRST_NAIL - LENGTH_OF_OPENNING));().add(new Line(centerX + HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX + HGAP / 2, Y_FOR_FIRST_NAIL - LENGTH_OF_OPENNING));Not needed for running from the command line.*/public static void main(String[] args) { launch(args);}}。
第13章习题参考答案一、简答题1.什么是事件?事件处理包括哪些因素?答:Java对事件的处理采用授权的事件模型,也成为委托事件模型。
在授权事件模型中,事件是一个描述事件源状态改变的对象。
通过鼠标、键盘与GUI直接或间接交互都会产生事件,按回车键、单击按钮、在一个下拉列表中选择一个选项等操作。
程序有时需对发生的事件作出反应来实现特定的任务。
事件处理主要包括:事件、事件源和监听器(事件处理者)。
事件是由事件源产生,事件源可以是GUI组件、JavaBen或由生成事件能力的对象。
事件发生后,组件本身并不处理,需要交给监听器(另外一个类)来处理。
实际上监听器也可称为事件处理者。
监听器对象属于一个类的实例,这个类实现了一个特殊的接口,名为"监听器接口"。
监听器负责处理事件源发生的事件,监听器是一个对象,为了处理事件源发生的事件,监听器会自动调用一个方法来处理事件.对每个明确的事件的产生,都相应地定义一个明确的Java方法。
2.请具体说明Java的事件处理机制中涉及到哪些方面?答:Java对事件的处理采用授权的事件模型,即委托代理模型。
委托代理模型(Delegation model)的原理是:当事件产生时,该事件被送到产生该事件的组件去处理,而要能够处理这个事件,该组件必须注册(register)有与该事件有关的一个或多个被称为listeners监听器的类,这些类包含了相应的方法能接受事件并对事件进行处理,包括如下处理过程:(1)确定事件源图形界面的每个可能产生事件的组件称为事件源,不同事件源上发生的事件的种类不同。
(2)注册事件源如果希望事件源上发生的事件被程序处理,就要把事件源注册给能够处理该事件源上那种类型的事件监听器。
监听器是属于一个类的实例,这个类实现了一个特殊的接口,名为“监听器接口”。
(3)委托处理事件当事件源上发生监听者可以处理的事件时,事件源把这个事件作为实际参数传递给监听者中负责处理这类事件的方法,该方法根据事件对象中封装的信息来确定如何响应这个事件。
java基础入门课后习题答案Java基础入门课后习题答案Java是一门广泛应用于软件开发领域的编程语言,掌握Java的基础知识对于想要从事软件开发的人来说是非常重要的。
在学习Java的过程中,课后习题是巩固知识和提高编程能力的重要途径。
本文将为大家提供一些Java基础入门课后习题的答案,希望能够对大家的学习有所帮助。
一、基础语法题1. 编写一个Java程序,输出"Hello, World!"。
```javapublic class HelloWorld {public static void main(String[] args) {System.out.println("Hello, World!");}}```2. 编写一个Java程序,计算并输出1到100之间所有偶数的和。
```javapublic class SumOfEvenNumbers {public static void main(String[] args) {int sum = 0;for (int i = 2; i <= 100; i += 2) {sum += i;System.out.println("1到100之间所有偶数的和为:" + sum); }}```3. 编写一个Java程序,判断一个数是否为素数。
```javapublic class PrimeNumber {public static void main(String[] args) {int num = 17;boolean isPrime = true;for (int i = 2; i <= Math.sqrt(num); i++) {if (num % i == 0) {isPrime = false;break;}}if (isPrime) {System.out.println(num + "是素数");} else {System.out.println(num + "不是素数");}}```二、面向对象题1. 编写一个Java类,表示一个学生,包含学生的姓名和年龄,并提供获取和设置姓名、年龄的方法。
Java语言程序设计课后习题答案全集Java语言程序设计是一门广泛应用于软件开发领域的编程语言,随着其应用范围的不断扩大,对于掌握Java编程技巧的需求也逐渐增加。
为了帮助读者更好地掌握Java编程,本文将提供Java语言程序设计课后习题的全集答案,供读者参考。
一、基础知识题1. 代码中的注释是什么作用?如何使用注释.答:注释在代码中是用来解释或者说明代码的功能或用途的语句,编译器在编译代码时会自动忽略注释。
在Java中,有三种注释的方式:- 单行注释:使用"// " 可以在代码的一行中加入注释。
- 多行注释:使用"/* */" 可以在多行中添加注释。
- 文档注释:使用"/** */" 可以添加方法或类的文档注释。
2. 什么是Java的数据类型?请列举常见的数据类型。
答:Java的数据类型用来指定变量的类型,常见的数据类型有:- 基本数据类型:包括整型(byte、short、int、long)、浮点型(float、double)、字符型(char)、布尔型(boolean)。
- 引用数据类型:包括类(class)、接口(interface)、数组(array)等。
二、代码编写题1. 编写Java程序,输入两个整数,求和并输出结果。
答:```javaimport java.util.Scanner;public class SumCalculator {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入第一个整数:");int num1 = scanner.nextInt();System.out.print("请输入第二个整数:");int num2 = scanner.nextInt();int sum = num1 + num2;System.out.println("两个整数的和为:" + sum);}}```三、综合应用题1. 编写Java程序,实现学生信息管理系统,要求包括以下功能:- 添加学生信息(姓名、年龄、性别、学号等);- 修改学生信息;- 删除学生信息;- 查询学生信息。
第一章1.1 public class Test{public static void main(String[] args){System.out.println("Welcome to Java !");System.out.println("Welcome to Computer Science !");System.out.println("Programming is fun .");}}1.2 public class Test{public static void main(String[] args){for(int i = 0;i <= 4;i++){System.out.println("Welcome to Java !");}}}1.3 public class Test{public static void main(String[] args){System.out.println(" ]");System.out.println(" ]");System.out.println("] ]");System.out.println(" ]]");}}public class Test{public static void main(String[] args){System.out.println(" A");System.out.println(" A A");System.out.println(" AAAAA");System.out.println("A A");}}public class Test{public static void main(String[] args){System.out.println("V V");System.out.println(" V V");System.out.println(" V V");System.out.println(" V");}}1.4 public class Test{public static void main(String[] args){System.out.println("a a^2 a^3");System.out.println("1 1 1");System.out.println("2 4 8");System.out.println("3 9 27");System.out.println("4 16 64");}}1.5 public class Test{public static void main(String[] args){System.out.println((9.5*4.5-2.5*3)/(45.5-3.5));}}1.6 public class Test{public static void main(String[] args){int i = 1,sum = 0;for(;i <= 9;i++)sum += i;System.out.println(sum);}}1.7 public class Test{public static void main(String[] args){System.out.println(4*(1.0-1.0/3+1.0/5-1.0/7+1.0/9-1.0/11));System.out.println(4*(1.0-1.0/3+1.0/5-1.0/7+1.0/9-1.0/11+1.0/13)) ;}}1.8 public class Test{public static void main(String[] args){final double PI = 3.14;double radius = 5.5;System.out.println(2 * radius * PI);System.out.println(PI * radius * radius);}}1.9 public class Test{public static void main(String[] args){System.out.println(7.9 * 4.5);System.out.println(2 * (7.9 + 4.5));}}1.10 public class Test{public static void main(String[] args){double S = 14 / 1.6;double T = 45 * 60 + 30;double speed = S / T;System.out.println(speed);}}1.11public class Test{public static void main(String[] args){int BN = 312032486; //original person numbersdouble EveryYS,EveryYBP,EveryYDP,EveryYMP;EveryYS = 365 * 24 * 60 * 60;EveryYBP = EveryYS / 7;EveryYDP = EveryYS / 13;EveryYMP = EveryYS / 45;int FirstYP,SecondYP,ThirdYP,FourthYP,FivthYP;FirstYP = (int)(BN + EveryYBP + EveryYMP - EveryYDP);SecondYP = (int)(FirstYP + EveryYBP + EveryYMP - EveryYDP);ThirdYP = (int)(SecondYP + EveryYBP + EveryYMP - EveryYDP);FourthYP = (int)(ThirdYP + EveryYBP + EveryYMP - EveryYDP);FivthYP = (int)(FourthYP + EveryYBP + EveryYMP - EveryYDP);System.out.println(FirstYP);System.out.println(SecondYP);System.out.println(ThirdYP);System.out.println(FourthYP);System.out.println(FivthYP);}}1.12 public class Test{public static void main(String[] args){double S = 24 * 1.6;double T = (1 * 60 + 40) * 60 + 35;double speed = S / T;System.out.println(speed);}}1.13 import java.util.Scanner;public class Test{public static void main(String[] args){Scanner input = new Scanner(System.in);System.out.println("input a,b,c,d,e,f value please:");double a = input.nextDouble();double b = input.nextDouble();double c = input.nextDouble();double d = input.nextDouble();double e = input.nextDouble();double f = input.nextDouble();double x,y;x = (e * d - b * f) / (a * d - b * c);y = (a * f - e * c) / (a * d - b * c);System.out.println("The result is x: "+(int)(x * 1000) / 1000.0);System.out.println("The result is y: "+(int)(y * 1000) / 1000.0);}}。
第13章 创建图形用户界面复习题13.1 答:Swing 组件中均定义了以下三个方法:z public void setBackground (Color bg),设置此组件的背景色。
z public void setForeground (Color fg),设置此组件的前景色。
z public void setFont (Font font),设置此组件的字体。
这三个方法原始定义在类javax.swing.JComponent 中。
13.2 答:方法如下:JButton btn = new JButton("OK"); //创建一个“OK”按钮btn.setText("确认"); //将按钮上的文字改为“确认”ImageIcon image = new ImageIcon("D:/b1.gif"); //创建图标对象btn.setIcon(image); //设置按钮上的图标为指定的image 对象13.3 答:由于在javax.swing.JComponent 类中定义了如下方法,因此,其子类均可以设置一个边框。
public void setBorder(Border border),设置此组件的边框。
给面板设置带标题的边框的语句如下:JPanel panel = new JPanel(); //创建面板对象TitledBorder border = new TitledBorder("Title"); //创建标题边框对象 panel.setBorder(border); //将panel 的边框设置为border说明:边框类均在javax.swing.border 包中,使用时要导入。
13.4 答:Component c1 = new Component();出错,原因是Component 是抽象类,不能创建对象JComponent c2 = new JComponent();课后答案网ww w.kh da w .c om出错,原因是JComponent 是抽象类,不能创建对象c5.add(c6);出错,原因是add 方法的声明为:public Component add (Component comp),不能接收Object 类型的参数。
01public 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);}}classTriangleNew extends GeometricObject {private double side1 = 1.0, side2 = 1.0, side3 = 1.0;/** Constructor */publicTriangleNew() {}/** Constructor */publicTriangleNew(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;returnMath.sqrt(s * (s - side1) * (s - side2) * (s - side3));}/** Implement the abstract method findCircumference in* GeometricObject**/public double getPerimeter() {return side1 + side2 + side3;}@Overridepublic String toString() {// Implement it to return the three sidesreturn "TriangleNew: side1 = " + side1 + " side2 = " + side2 + " side3 = " + side3;}}02importjava.util.ArrayList;public class Exercise13_02 {public static void main(String[] args) {ArrayList<Number> list = new ArrayList<Number>();list.add(14);list.add(24);list.add(4);list.add(42);list.add(5);shuffle(list);for (inti = 0; i<list.size(); i++)System.out.print(list.get(i) + " ");}public static void shuffle(ArrayList<Number> list) {for (inti = 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);}}}03importjava.util.ArrayList;public class Exercise13_03 {public static void main(String[] args) {ArrayList<Number> list = new ArrayList<Number>();list.add(14);list.add(24);list.add(4);list.add(42);list.add(5);sort(list);for (inti = 0; i<list.size(); i++)System.out.print(list.get(i) + " ");}public static void sort(ArrayList<Number> list) {for (inti = 0; i<list.size() - 1; i++) {// Find the minimum in the list[i..list.length-1]Number currentMin = list.get(i);intcurrentMinIndex = 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);}}}}04importjava.util.*;public class Exercise13_04 {staticMyCalendar 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 yearyear = 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 yearmonth = Integer.parseInt(args[0]);calendar.set(Calendar.MONTH, month-1);}//set date to the first day in a monthcalendar.set(Calendar.DATE, 1);//print calendar for the monthprintMonth(year, month);}static void printMonth(int year, int month) {//get start day of the week for the first date in the month intstartDay = getStartDay();//get number of days in the month intnumOfDaysInMonth = calendar.daysInMonth();//print headingsprintMonthTitle(year, month);//print bodyprintMonthBody(startDay, numOfDaysInMonth);}staticintgetStartDay() {returncalendar.get(Calendar.DAY_OF_WEEK);}static void printMonthBody(intstartDay, intnumOfDaysInMonth) { //print padding space before the first day of the monthinti = 0;for (i = 0; i< startDay-1; i++)System.out.print(" ");for (i = 1; i<= numOfDaysInMonth; i++) {if (i< 10)System.out.print(" "+i);elseSystem.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()+", "+year); System.out.println("-----------------------------");System.out.println(" Sun Mon Tue Wed Thu Fri Sat");}}05public class Exercise13_05 {// Main methodpublic static void main(String[] args) {// Create two comparable circlesCircle1 circle1 = new Circle1(5);Circle1 circle2 = new Circle1(4);// Display the max circleCircle1 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<GeometricObject1> { protected String color;protected double weight;// Default constructprotected GeometricObject1() {color = "white";weight = 1.0;}// Construct a geometric objectprotected GeometricObject1(String color, double weight) {this.color = color;this.weight = weight;// Getter method for colorpublic String getColor() {return color;}// Setter method for colorpublic void setColor(String color) {this.color = color;}// Getter method for weightpublic double getWeight() {return weight;}// Setter method for weightpublic void setWeight(double weight) {this.weight = weight;}// Abstract methodpublic abstract double getArea();// Abstract methodpublic abstract double getPerimeter();publicintcompareTo(GeometricObject1 o) {if (getArea() <o.getArea())return -1;else if (getArea() == o.getArea())return 0;elsereturn 1;}public static GeometricObject1 max(GeometricObject1 o1, GeometricObject1 o2) { if (pareTo(o2) > 0)return o1;elsereturn o2;}}// Circle.java: The circle class that extends GeometricObjectclass Circle1 extends GeometricObject1 {protected double radius;// Default constructorpublic Circle1() {this(1.0, "white", 1.0);}// Construct circle with specified radiuspublic Circle1(double radius) {super("white", 1.0);this.radius = radius;}// Construct a circle with specified radius, weight, and colorpublic Circle1(double radius, String color, double weight) {super(color, weight);this.radius = radius;}// Getter method for radiuspublic double getRadius() {return radius;}// Setter method for radiuspublic 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 publicboolean equals(Circle1 circle) {returnthis.radius == circle.getRadius();}@Overridepublic String toString() {return "[Circle] radius = " + radius;}@OverridepublicintcompareTo(GeometricObject1 o) {if (getRadius() > ((Circle1) o).getRadius())return 1;else if (getRadius() < ((Circle1) o).getRadius())return -1;elsereturn 0;}}06public class Exercise13_06 {// Main methodpublic static void main(String[] args) {// Create two comarable rectanglesComparableCircle circle1 = new ComparableCircle(5);ComparableCircle circle2 = new ComparableCircle(15);// Display the max rectComparableCircle circle3 = (ComparableCircle)Max.max(circle1, circle2); System.out.println("The max circle's radius is " + circle3.getRadius());System.out.println(circle3);}}classComparableCircle extends Circle implements Comparable<ComparableCircle> { /** Construct a ComparableRectangle with specified properties */ publicComparableCircle(double radius) {super(radius);}@OverridepublicintcompareTo(ComparableCircle o) {if (getRadius() >o.getRadius())return 1;else if (getRadius() <o.getRadius())return -1;elsereturn 0;}}//Max.java: Find a maximum objectclass Max {/** Return the maximum of two objects */public static ComparableCircle max(ComparableCircle o1, ComparableCircle o2) {if (pareTo(o2) > 0)return o1;elsereturn o2;}}07public 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 (inti = 0; i<objects.length; i++) {System.out.println("Area is " + objects[i].getArea());if (objects[i] instanceof Colorable)((Colorable)objects[i]).howToColor();}}}interface Colorable {voidhowToColor();}class Square extends GeometricObject implements Colorable {private double side;public Square(double side) {this.side = side;}@Overridepublic void howToColor() {System.out.println("Color all four sides");}@Overridepublic double getArea() {return side * side;}@Overridepublic double getPerimeter() {return 4 * side;}}08importjava.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 { privateArrayList<Object> list = new ArrayList<Object>();publicbooleanisEmpty() {returnlist.isEmpty();}publicintgetSize() {returnlist.size();}public Object peek() {returnlist.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<Object>) this.list.clone(); return c;} catch (CloneNotSupportedException ex) { return null;}}}09public 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(pareTo(obj2));}}// Circle.java: The circle class that extends GeometricObjectclass Circle13_09 extends GeometricObject implements Comparable<Circle13_09> { 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;}@Overridepublic String toString() {return "[Circle] radius = " + radius;}@OverridepublicintcompareTo(Circle13_09 obj) {if (this.getArea() >obj.getArea())return 1;else if (this.getArea() <obj.getArea())return -1;elsereturn 0;}publicboolean equals(Object obj) {returnthis.radius == ((Circle13_09)obj).radius;}}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(pareTo(obj2));}}// Rectangle.java: The Rectangle class that extends GeometricObjectclass Rectangle13_10 extends GeometricObject implements Comparable<Rectangle13_10> { 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);}@Overridepublic String toString() {return "[Rectangle] width = " + width +" and height = " + height;}@OverridepublicintcompareTo(Rectangle13_10 obj) {if (this.getArea() >obj.getArea())return 1;else if (this.getArea() <obj.getArea())return -1;elsereturn 0;}publicboolean equals(Object obj) {returnthis.getArea() == ((Rectangle13_10)obj).getArea();}}11public 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 " + pareTo(a2)); }}class Octagon extends GeometricObjectimplements Comparable<Octagon>, Cloneable {private double side;/** Construct a Octagon with the default side */public Octagon () {// Implement itthis.side = 1;}/** Construct a Octagon with the specified side */public Octagon (double side) {// Implement itthis.side = side;}@Override /** Implement the abstract method getArea in GeometricObject */public double getArea() {// Implement itreturn (2 + 4 / Math.sqrt(2)) * side * side;}@Override /** Implement the abstract method getPerimeter in GeometricObject */public double getPerimeter() {// Implement itreturn 8 * side;}@OverridepublicintcompareTo(Octagon obj) {if (this.side>obj.side)return 1;else if (this.side == obj.side)return 0;elsereturn -1;}@Override /** Implement the clone method inthe Object class */public Object clone() {// Octagon o = new Octagon();// o.side = this.side;// return o;//// Implement ittry {returnsuper.clone(); // Automatically perform a shallow copy }catch (CloneNotSupportedException ex) {return null;}}}12public 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 (inti = 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*/ publicboolean equals(Rectangle rectangle) {return (width == rectangle.getWidth()) &&(height == rectangle.getHeight());}@Overridepublic String toString() {return "[Rectangle] width = " + width +" and height = " + height;}}13public 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]; privateintnumberOfStudents;public Course1(String courseName) {this.courseName = courseName;}public void addStudent(String student) {students[numberOfStudents] = student; numberOfStudents++;}public String[] getStudents() {return students;}publicintgetNumberOfStudents() { returnnumberOfStudents;}public String getCourse1Name() {returncourseName;}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;}}}14classNewRational extends Number implements Comparable<NewRational> { // Data fields for numerator and denominatorprivate long[] r = new long[2];/**Default constructor*/publicNewRational() {this(0, 1);}/**Construct a rational with specified numerator and denominator*/ publicNewRational(long numerator, long denominator) {longgcd = 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*/ publicNewRational add(NewRationalsecondNewRational) { 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*/ publicNewRational subtract(NewRationalsecondNewRational) { 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*/ publicNewRational multiply(NewRationalsecondNewRational) { long n = r[0]*secondNewRational.getNumerator();long d = r[1]*secondNewRational.getDenominator();return new NewRational(n, d);}/**Divide a rational number from this rational*/ publicNewRational divide(NewRationalsecondNewRational) {long n = r[0]*secondNewRational.getDenominator();long d = r[1]*secondNewRational.r[0];return new NewRational(n, d);}@Overridepublic String toString() {if (r[1] == 1)return r[0] + "";elsereturn r[0] + "/" + r[1];}/**Override the equals method*/publicboolean equals(Object parm1) {/**@todo: Override this ng.Object method*/if ((this.subtract((NewRational)(parm1))).getNumerator() == 0) return true;elsereturn false;}/**Override the intValue method*/publicintintValue() {/**@todo: implement this ng.Number abstract method*/ return (int)doubleValue();}/**Override the floatValue method*/public float floatValue() {/**@todo: implement this ng.Number abstract method*/ return (float)doubleValue();}/**Override the doubleValue method*/public double doubleValue() {/**@todo: implement this ng.Number abstract method*/ return r[0]*1.0/r[1];}/**Override the longValue method*/public long longValue() {/**@todo: implement this ng.Number abstract method*/ return (long)doubleValue();}@OverridepublicintcompareTo(NewRational o) {/**@todo: Implement this parable method*/if ((this.subtract((NewRational)o)).getNumerator() > 0)return 1;else if ((this.subtract((NewRational)o)).getNumerator() < 0)return -1;elsereturn 0;}}15importjava.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 resultsSystem.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<Rational> { // Data fields for numerator and denominatorprivateBigInteger numerator = BigInteger.ZERO;privateBigInteger 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) {BigIntegergcd = gcd(numerator, denominator);if (pareTo(BigInteger.ZERO) < 0)this.numerator = numerator.multiply(new BigInteger("-1")).divide(gcd); elsethis.numerator = numerator.divide(gcd);this.denominator = denominator.abs().divide(gcd);}/** Find GCD of two numbers */private static BigIntegergcd(BigInteger n, BigInteger d) {BigInteger n1 = n.abs();BigInteger n2 = d.abs();BigIntegergcd = BigInteger.ONE;for (BigInteger k = BigInteger.ONE;pareTo(n1) <= 0 &&pareTo(n2) <= 0;k = k.add(BigInteger.ONE)) {if (n1.remainder(k).equals(BigInteger.ZERO) &&n2.remainder(k).equals(BigInteger.ZERO))gcd = k;}returngcd;}/** Return numerator */publicBigIntegergetNumerator() {return numerator;}/** Return denominator */ publicBigIntegergetDenominator() {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);}@Overridepublic String toString() {if (denominator.equals(BigInteger.ONE))return numerator + "";elsereturn numerator + "/" + denominator;}@Override /** Override the equals method in the Object class */ publicboolean equals(Object parm1) {if ((this.subtract((Rational)(parm1))).getNumerator().equals(BigInteger.ONE)) return true;elsereturn false;}@Override /** Override the hashCode method in the Object class */ publicinthashCode() {return new Double(this.doubleValue()).hashCode();}@Override /** Override the abstract intValue method in ng.Number */publicintintValue() {return (int)doubleValue();}@Override /** Override the abstract floatValue method in ng.Number */ public float floatValue() {return (float)doubleValue();}@Override /** Override the doubleValue method in ng.Number */ public double doubleValue() {returnnumerator.doubleValue() / denominator.doubleValue();}@Override /** Override the abstract longValue method in ng.Number */ public long longValue() {return (long)doubleValue();}@OverridepublicintcompareTo(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;elsereturn 0;}}}16public 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("/");intnumer = Integer.parseInt(st[0]);intdenom = Integer.parseInt(st[1]);return new Rational(numer, denom);}}/* Alternatively, you can use StringTokenizer. See Supplement III.AA on StringTokenizer as alternativeimportjava.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]));}。