java语言程序设计基础篇第十版课后答案
java语言程序设计基础篇第十版第十三章练习标准答案
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]));}。
《Java语言程序设计(基础篇)》(第10版 梁勇 著)第九章练习题答案
《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;}}。
《Java语言程序设计(基础篇)》(第10版 梁勇 著)第三十二章练习题答案
《Java语言程序设计(基础篇)》(第10版梁勇著)第三十二章练习题答案32.1import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import bel;import javafx.scene.control.TextField;import yout.BorderPane;import yout.HBox;import yout.VBox;import javafx.stage.Stage;public class Exercise32_01 extends Application {private Button btView = new Button("View");private Button btInsert = new Button("Insert");private Button btUpdate = new Button("Update");private Button btClear = new Button("Clear");private TextField tfID = new TextField();private TextField tfLastName = new TextField();private TextField tfFirstName = new TextField();private TextField tfMi = new TextField();private TextField tfAddress = new TextField();private TextField tfCity = new TextField();private TextField tfState = new TextField();private TextField tfTelephone = new TextField();private Label lblStatus = new Label();// The Statement for processing queriesprivate Statement stmt;@Override // Override the start method in the Application class public void start(Stage primaryStage) {VBox vBox = new VBox(5);HBox hBox1 = new HBox(5);hBox1.getChildren().addAll(new Label("ID"), tfID);HBox hBox2 = new HBox(5);hBox2.getChildren().addAll(new Label("Last Name"), tfLastName, new Label("First Name"), tfFirstName, new Label("MI"), tfMi);tfLastName.setPrefColumnCount(8);tfFirstName.setPrefColumnCount(8);tfMi.setPrefColumnCount(1);HBox hBox3 = new HBox(5);hBox3.getChildren().addAll(new Label("Address"), tfAddress);HBox hBox4 = new HBox(5);hBox4.getChildren().addAll(new Label("City"), tfCity,new Label("State"), tfState);HBox hBox5 = new HBox(5);hBox5.getChildren().addAll(new Label("Telephone"), tfTelephone); vBox.getChildren().addAll(hBox1, hBox2, hBox3, hBox4, hBox5);HBox hBox = new HBox(5);hBox.getChildren().addAll(btView, btInsert, btUpdate, btClear);hBox.setAlignment(Pos.CENTER);BorderPane pane = new BorderPane();pane.setCenter(vBox);pane.setTop(lblStatus);pane.setBottom(hBox);// Create a scene and place it in the stageScene scene = new Scene(pane, 400, 200);primaryStage.setTitle("ExtraExercise32_01"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stageinitializeDB();btView.setOnAction(e -> view());btInsert.setOnAction(e -> insert());btUpdate.setOnAction(e -> update());btClear.setOnAction(e -> clear());}private void initializeDB() {try {// Connect to the local InterBase databaseConnection conn = DriverManager.getConnection// ("dbc:odbc:exampleMDBDataSource", "", "" );("jdbc:mysql://localhost/javabook", "scott", "tiger");System.out.println("Database connected\n");lblStatus.setText("Database connected");// Create a statementstmt = conn.createStatement();}catch (Exception ex) {lblStatus.setText("Connection failed: " + ex);}}/**View record by ID*/private void view() {// Build a SQL SELECT statementString query = "SELECT * FROM Staff WHERE ID = "+ "'" + tfID.getText().trim() + "'";try {// Execute queryResultSet rs = stmt.executeQuery(query);loadToTextField(rs);}catch(SQLException ex) {lblStatus.setText("Select failed: " + ex);}}/**Load the record into text fields*/private void loadToTextField(ResultSet rs) throws SQLException { if (rs.next()) {tfLastName.setText(rs.getString(2));tfFirstName.setText(rs.getString(3));tfMi.setText(rs.getString(4));tfAddress.setText(rs.getString(5));tfCity.setText(rs.getString(6));tfState.setText(rs.getString(7));tfTelephone.setText(rs.getString(8));lblStatus.setText("Record found");}elselblStatus.setText("Record not found");}/**Insert a new record*/private void insert() {// Build a SQL INSERT statementString insertStmt ="INSERT INTO Staff(ID, LastName, FirstName, mi, Address, " + " City, State, Telephone) VALUES('" +tfID.getText().trim() + "','" +tfLastName.getText().trim() + "','" +tfFirstName.getText().trim() + "','" +tfMi.getText().trim() + "','" +tfAddress.getText().trim() + "','" +tfCity.getText().trim() + "','" +tfState.getText().trim() + "','" +tfTelephone.getText().trim() + "');";try {stmt.executeUpdate(insertStmt);}catch (SQLException ex) {lblStatus.setText("Insertion failed: " + ex);}lblStatus.setText("record inserted");}/**Update a record*/private void update() {// Build a SQL UPDATE statementString updateStmt = "UPDATE Staff " +"SET LastName = '" + tfLastName.getText().trim() + "'," +"FirstName = '" + tfFirstName.getText().trim() + "'," +"mi = '" + tfMi.getText().trim() + "'," +"Address = '" + tfAddress.getText().trim() + "'," +"City = '" + tfCity.getText().trim() + "'," +"State = '" + tfState.getText().trim() + "'," +"Telephone = '" + tfTelephone.getText().trim() + "' " +"WHERE ID = '" + tfID.getText().trim() + "'";try {stmt.executeUpdate(updateStmt);lblStatus.setText("Record updated");}catch(SQLException ex) {lblStatus.setText("Update failed: " + ex);}}/**Clear text fields*/private void clear() {tfID.setText(null);tfLastName.setText(null);tfFirstName.setText(null);tfMi.setText(null);tfAddress.setText(null);tfCity.setText(null);tfState.setText(null);tfTelephone.setText(null);}/*** The main method is only needed for the IDE with limited* avaFX support. Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}32.2import java.sql.*;import javafx.scene.Scene;import yout.HBox;import javafx.stage.Stage;import javafx.application.Application;public class Exercise32_02 extends Application {private String[] dataName;private double[] data;@Override // Override the start method in the Application class public void start(Stage primaryStage) {initializeDB();ChartModel chartModel = new ChartModel();chartModel.setChartData(dataName, data);PieChart pieChart = new PieChart();BarChart barChart = new BarChart();HBox hBox = new HBox(5);hBox.getChildren().addAll(pieChart, barChart);// Create a scene and place it in the stageScene scene = new Scene(hBox, 420, 80);primaryStage.setTitle("Exercise32_02"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagepieChart.setModel(chartModel);barChart.setModel(chartModel);}private void initializeDB() {try {Connection conn = DriverManager.getConnection// ("dbc:odbc:exampleMDBDataSource", "", "" );("jdbc:mysql://localhost/javabook", "scott", "tiger");System.out.println("Database connected\n");// Connect to the sample databaseStatement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery("select deptId, count(*) from Student where deptId is not null group by deptId;");// Count rowsint count = 0;while (rs.next()) {count++;}dataName = new String[count];data = new double[count];// We have to obtain the result set againrs = stmt.executeQuery("select deptId, count(*) from Student where deptId is not null group by deptId;");int i = 0;while (rs.next()) {dataName[i] = rs.getString(1);data[i] = rs.getInt(2);i++;}}catch (Exception ex) {ex.printStackTrace();}}/*** 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);}}32.3import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import bel;import javafx.scene.control.TextField;import javafx.stage.Stage;import java.sql.*;import javafx.collections.FXCollections;import javafx.geometry.HPos;import boBox;import javafx.scene.control.PasswordField;import yout.BorderPane;import yout.GridPane;public class Exercise32_03 extends Application {@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {// Create a scene and place it in the stageScene scene = new Scene(new DBConnectionPane(), 420, 80);primaryStage.setTitle("DB Connection"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage}/*** 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);}}class DBConnectionPane extends BorderPane {private Connection connection;private Label lblConnectionStatus = new Label("No connection");private Button btConnect = new Button("Connect to DB");private ComboBox<String> cboDriver = new ComboBox<>(FXCollections.observableArrayList("com.mysql.jdbc.Driver", "sun.jdbc.odbc.JdbcOdbcDriver","oracle.jdbc.driver.OracleDriver"));private ComboBox<String> cboURL = new ComboBox<>(FXCollections.observableArrayList("jdbc:mysql://localhost/javabook","jdbc:odbc:exampleMDBDataSource","jdbc:oracle:thin:@:1521:ora9i"));private TextField tfUsername = new TextField();private PasswordField pfPassword = new PasswordField();/** Creates new form DBConnectionPanel */public DBConnectionPane() {cboDriver.setEditable(true);cboURL.setEditable(true);GridPane gridPane = new GridPane();gridPane.add(new Label("JDBC Drive"), 0, 0);gridPane.add(new Label("Database URL"), 0, 1);gridPane.add(new Label("Username"), 0, 2);gridPane.add(new Label("Password"), 0, 3);gridPane.add(cboDriver, 1, 0);gridPane.add(cboURL, 1, 1);gridPane.add(tfUsername, 1, 2);gridPane.add(pfPassword, 1, 3);gridPane.add(btConnect, 1, 4);GridPane.setHalignment(btConnect, HPos.RIGHT);this.setTop(lblConnectionStatus);this.setCenter(gridPane);btConnect.setOnAction(e -> connectDB());}private void connectDB() {// Get database information from the user inputString driver = cboDriver.getValue();String url = cboURL.getValue();String username = tfUsername.getText().trim();String password = new String(pfPassword.getText());// Connection to the databasetry {Class.forName(driver);connection = DriverManager.getConnection(url, username, password);lblConnectionStatus.setText("Connected to " + url); }catch (ng.Exception ex) {ex.printStackTrace();}}/** Return connection */public Connection getConnection() {return connection;}}32.4import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import bel;import javafx.scene.control.TextField;import javafx.stage.Stage;import javafx.scene.control.ScrollPane;import javafx.scene.control.TextArea;import yout.BorderPane;import yout.HBox;public class Exercise32_04 extends Application {private TextField tfSSN = new TextField();private TextArea taResult = new TextArea();private Label lblStatus = new Label();private Button btShowGrade = new Button("Show Grade");// Statement for executing queriesprivate Statement stmt;@Override // Override the start method in the Application class public void start(Stage primaryStage) {HBox hBox = new HBox(5);hBox.getChildren().addAll(new Label("SSN"), tfSSN,btShowGrade);hBox.setAlignment(Pos.CENTER);BorderPane pane = new BorderPane();pane.setCenter(new ScrollPane(taResult));pane.setTop(hBox);pane.setBottom(lblStatus);// Create a scene and place it in the stageScene scene = new Scene(pane, 420, 80);primaryStage.setTitle("Exercise32_04"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stageinitializeDB();btShowGrade.setOnAction(e -> showGrade());}private void initializeDB() {try {// Load the JDBC driverClass.forName("com.mysql.jdbc.Driver");System.out.println("Driver loaded");// Establish a connectionConnection connection = DriverManager.getConnection("jdbc:mysql://localhost/javabook", "scott", "tiger");// ("jdbc:oracle:thin:@:1521:ora9i",// "scott", "tiger");System.out.println("Database connected");// Create a statementstmt = connection.createStatement();}catch (Exception ex) {ex.printStackTrace();}}private void showGrade() {String ssn = tfSSN.getText();try {String queryString = "select firstName, mi, " +"lastName, title, grade from Student, Enrollment, Course " +"where Student.ssn = '" + ssn +"' and Enrollment.courseId = Course.courseId " +" and Enrollment.ssn = Student.ssn";ResultSet rset = stmt.executeQuery(queryString);taResult.setText(null);int countRow = 0;while (rset.next()) {String lastName = rset.getString(1);String mi = rset.getString(2);String firstName = rset.getString(3);String title = rset.getString(4);String grade = rset.getString(5);// Display resulttaResult.appendText(firstName + " " + mi +" " + lastName + "'s grade on course " + title + " is " +grade + "\n");countRow++;}if (countRow > 0)lblStatus.setText(countRow + " courses found");elselblStatus.setText("no courses found for this SSN");}catch (SQLException ex) {ex.printStackTrace();}}/*** 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);}}32.5import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.sql.Statement;import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import bel;import javafx.scene.control.TextField;import javafx.stage.Stage;import javafx.scene.control.ScrollPane;import javafx.scene.control.TextArea;import yout.BorderPane;import yout.HBox;public class Exercise32_05 extends Application {private TextField tfTableName = new TextField();private TextArea taResult = new TextArea();private Button btShowContents = new Button("Show Contents"); private Label lblStatus = new Label();// Statement for executing queriesprivate Statement stmt;@Override // Override the start method in the Application class public void start(Stage primaryStage) {HBox hBox = new HBox(5);hBox.getChildren().addAll(new Label("Table Name"), tfTableName, btShowContents);hBox.setAlignment(Pos.CENTER);BorderPane pane = new BorderPane();pane.setCenter(new ScrollPane(taResult));pane.setTop(hBox);pane.setBottom(lblStatus);// Create a scene and place it in the stageScene scene = new Scene(pane, 420, 80);primaryStage.setTitle("Exercise32_05"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stageinitializeDB();btShowContents.setOnAction(e -> showContents());}private void initializeDB() {try {// Load the JDBC driverClass.forName("com.mysql.jdbc.Driver");System.out.println("Driver loaded");// Establish a connectionConnection connection = DriverManager.getConnection("jdbc:mysql://localhost/javabook", "scott", "tiger");// ("jdbc:oracle:thin:@:1521:ora9i",// "scott", "tiger");System.out.println("Database connected");// Create a statementstmt = connection.createStatement();}catch (Exception ex) {ex.printStackTrace();}}private void showContents() {String tableName = tfTableName.getText();try {String queryString = "select * from " + tableName;ResultSet resultSet = stmt.executeQuery(queryString);ResultSetMetaData rsMetaData = resultSet.getMetaData();for (int i = 1; i <= rsMetaData.getColumnCount(); i++) {taResult.appendText(rsMetaData.getColumnName(i) + " "); }taResult.appendText("\n");// Iterate through the result and print the student nameswhile (resultSet.next()) {for (int i = 1; i <= rsMetaData.getColumnCount(); i++)taResult.appendText(resultSet.getObject(i) + " "); taResult.appendText("\n");}}catch (SQLException ex) {ex.printStackTrace();}}/*** 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);}}32.6import java.sql.Connection;import java.sql.DatabaseMetaData;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.sql.Statement;import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import boBox;import bel;import javafx.stage.Stage;import javafx.scene.control.ScrollPane;import javafx.scene.control.TextArea;import yout.BorderPane;import yout.HBox;public class Exercise32_06 extends Application {private ComboBox<String> cboTableName = new ComboBox<>(); private TextArea taResult = new TextArea();private Button btShowContents = new Button("Show Contents"); private Label lblStatus = new Label();// Statement for executing queriesprivate Statement stmt;@Override // Override the start method in the Application class public void start(Stage primaryStage) {HBox hBox = new HBox(5);hBox.getChildren().addAll(new Label("Table Name"),cboTableName, btShowContents);hBox.setAlignment(Pos.CENTER);BorderPane pane = new BorderPane();pane.setCenter(new ScrollPane(taResult));pane.setTop(hBox);pane.setBottom(lblStatus);// Create a scene and place it in the stageScene scene = new Scene(pane, 420, 80);primaryStage.setTitle("Exercise32_06"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stageinitializeDB();btShowContents.setOnAction(e -> showContents());}private void initializeDB() {try {// Load the JDBC driverClass.forName("com.mysql.jdbc.Driver");System.out.println("Driver loaded");// Establish a connectionConnection connection = DriverManager.getConnection("jdbc:mysql://localhost/javabook", "scott", "tiger");// ("jdbc:oracle:thin:@:1521:ora9i",// "scott", "tiger");System.out.println("Database connected");// Create a statementstmt = connection.createStatement();DatabaseMetaData dbMetaData = connection.getMetaData();ResultSet rsTables = dbMetaData.getTables(null, null, null,new String[] {"TABLE"}); System.out.print("User tables: ");while (rsTables.next()) {cboTableName.getItems().add(rsTables.getString("TABLE_NAME")); }cboTableName.getSelectionModel().selectFirst();}catch (Exception ex) {ex.printStackTrace();}}private void showContents() {String tableName = cboTableName.getValue();try {String queryString = "select * from " + tableName;ResultSet resultSet = stmt.executeQuery(queryString);ResultSetMetaData rsMetaData = resultSet.getMetaData();for (int i = 1; i <= rsMetaData.getColumnCount(); i++) {taResult.appendText(rsMetaData.getColumnName(i) + " "); }taResult.appendText("\n");// Iterate through the result and print the student nameswhile (resultSet.next()) {for (int i = 1; i <= rsMetaData.getColumnCount(); i++)taResult.appendText(resultSet.getObject(i) + " "); taResult.appendText("\n");}}catch (SQLException ex) {ex.printStackTrace();}}/*** 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);}}32.7/*Statement for creating a tablecreate table Quiz(questionId int,question varchar(4000),choicea varchar(1000),choiceb varchar(1000),choicec varchar(1000),choiced varchar(1000),answer varchar(5));*/import java.io.*;import java.util.*;import java.sql.*;public class Exercise32_07 {private ArrayList<Quiz> chapters = new ArrayList<Quiz>(); private PreparedStatement pstmt1;static class Quiz {String question = "";String choicea = "";String choiceb = "";String choicec = "";String choiced = "";String answer;String hint;}public static void main(String[] args) {new Exercise32_07();}/** Initialize global variables */public Exercise32_07() {try {readTest(chapters);initializeJdbc();int questionNo = 1;for (Quiz question : chapters) {storeQuiz(questionNo++, question);}}catch (Exception ex) {ex.printStackTrace();}}private void readTest(List<Quiz> testForAChapter) throwsException {// Create a buffered reader for reading questions from a fileBufferedReader in = new BufferedReader(new FileReader("Quiz.txt"));// Quiz countint questionCount = 0;boolean beginningOfQuiz = true; // for the first one// Text line from the question fileString line = "";Quiz question = null;// Read and process each line from the text fileloop:while ((line = in.readLine()) != null) {// Process a blank line in the text fileif (line.length() < 1) {continue;}// Determine question statement and multiple choicesif (line.charAt(0) == 'a' && line.charAt(1) == '.') {question.choicea = line.substring(2);}else if (line.charAt(0) == 'b' && line.charAt(1) == '.') {question.choiceb = line.substring(2);}else if (line.charAt(0) == 'c' && line.charAt(1) == '.') {question.choicec = line.substring(2);}else if (line.charAt(0) == 'd' && line.charAt(1) == '.') {question.choiced = line.substring(2);}else if (line.matches("(\\d)+\\..*")) { // Start a new questionbeginningOfQuiz = true;questionCount++; // Increase question countquestion = new Quiz(); // Create a new testtestForAChapter.add(question); // Add to the listquestion.question += line;}else if(line.toUpperCase().indexOf("ANSWER") == 0) { // End of question section// Extract answer and explanationStringTokenizer st = new StringTokenizer(line.substring(7),".\n\r\t ");question.answer = st.nextToken().toUpperCase();if (st.hasMoreTokens()) {question.hint = st.nextToken("\n\r");}}else if (line.charAt(0) == ' ') { // Process spaces before lineString spaces = "";for (int j = 0;((j < line.length()) && (line.charAt(j) == ' ')); j++) { spaces += " ";}question.question += spaces;question.question += line;}else {if (beginningOfQuiz && Character.isDigit(line.charAt(0)) &&line.charAt(1) == '.') {question.question += line.substring(2);beginningOfQuiz = false;}else if (beginningOfQuiz && Character.isDigit(line.charAt(0)) &&Character.isDigit(line.charAt(1))&& line.charAt(2) == '.') {question.question += line.substring(3);beginningOfQuiz = false;}else {question.question += line;}}}// Close the filein.close();}/** Initialize database connection */private void initializeJdbc() {try {// Load the JDBC driverClass.forName("com.mysql.jdbc.Driver");System.out.println("Driver loaded");// Declare driver and connection string// String connectionString = "jdbc:odbc:exampleMDBDataSource";// For MySQLString connectionString = "jdbc:mysql://localhost/javabook";// For Oracle// String connectionString = "jdbc:oracle:" +//"thin:scott/tiger@:1521:orcl";// Connect to the sample databaseConnection conn = DriverManager.getConnection(connectionString, "scott", "tiger");// Create a statement to insert questionspstmt1 = conn.prepareStatement("insert into Quiz " +"(questionId, question, choicea, choiceb, choicec, choiced, answer)" + "values (?, ?, ?, ?, ?, ?, ?)");}catch (Exception ex) {ex.printStackTrace();}}/** Store a question to the database */private void storeQuiz(int questionNo,Quiz question) throws SQLException {pstmt1.setInt(1, questionNo);pstmt1.setString(2, question.question);pstmt1.setString(3, question.choicea);pstmt1.setString(4, question.choiceb);pstmt1.setString(5, question.choicec);pstmt1.setString(6, question.choiced);pstmt1.setString(7, question.answer);pstmt1.executeUpdate();}}32.8import java.util.*;import java.sql.*;public class Exercise32_08 {private Statement stmt;。
Java语言程序设计(基础篇)第10版习题答案Chapter9-1
Java语⾔程序设计(基础篇)第10版习题答案Chapter9-1(矩形类 Rectangle)遵照9.2节中 Circle 类的例⼦,设计⼀个名为 Rectangle 的类表⽰矩形。
这个类包括:两个名为 width 和 height 的 double 型数据域,它们分别表⽰矩形的宽和⾼。
width 和 height 的默认值都为1。
创建默认矩形的⽆参构造⽅法⼀个创建 width 和 height 为指定值的矩形的构造⽅法。
⼀个名为 getArea() 的⽅法返回这个矩形的⾯积。
⼀个名为 getPerimeter() 的⽅法返回周长。
画出该矩形的 UML 图并实现这个类。
编写⼀个测试程序,创建两个 Rectangle 对象——⼀个矩形的宽为 4 ⽽⾼为 40,另⼀个矩形的宽为3.5 ⽽⾼为 35.9 。
按照这个顺序显⽰每个矩形的宽、⾼、⾯积、周长。
程序代码:public class Rectangle {private double width;private double height;public Rectangle(){width=1.0;height=1.0;}public Rectangle(double width,double height) {this.width=width;this.height=height;}public double getWidth() {return width;}public double getHeight() {return height;}public double getArea() {return width*height;}public double getPerimeter() {return 2*(width+height);}public static void main(String[] args) {// TODO Auto-generated method stubRectangle t1=new Rectangle(4,40);Rectangle t2=new Rectangle(3.5,35.9);System.out.println("width:"+t1.getWidth()+" height:"+t1.getHeight()+" Area:"+t1.getArea()+" Per:"+t1.getPerimeter());System.out.println("width:"+t2.getWidth()+" height:"+t2.getHeight()+" Area:"+t2.getArea()+" Per:"+t2.getPerimeter());}}运⾏结果:width:4.0 height:40.0 Area:160.0 Per:88.0width:3.5 height:35.9 Area:125.64999999999999 Per:78.8。
java语言程序设计基础篇第十版练习答案精编
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);}}。
java语言程序设计基础篇第十版第十四章练习答案
}
}
// Create a scene and place it in the stage
Scene scene = new Scene(pane);
primaryStage.setTitle("Exercise14_02"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
02Байду номын сангаас
public class Exercise14_02 extends Application {
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}}
05
public class Exercise14_05 extends Application {
for (int i = 0; i < 5; i++) {
Text txt = new Text("Java");
txt.setRotate(90);
txt.setFont(font);
txt.setFill(new Color(Math.random(), Math.random(), Math.random(), Math.random()));
java语言程序设计基础篇第十版第十三章练习答案
01public class Exercise13_01 { public static void main(String[] args) { TriangleNew triangle = new TriangleNew(1, , 1);("yellow");(true);"The area is " + ());"The perimeter is "+ ());}}class TriangleNew extends GeometricObject { private double side1 = , side2 = , side3 = ;/** Constructor */public TriangleNew() {}/** Constructor */public TriangleNew(double side1, double side2, double side3) { = side1;= side2;= side3;}/** Implement the abstract method findArea in GeometricObject */ public double getArea() {double s = (side1 + side2 + side3) / 2;return (s * (s - side1) * (s - side2) * (s - side3));}/** Implement the abstract method findCircumference in* GeometricObject**/public double getPerimeter() { return side1 + side2 + side3;}@Overridepublic String toString() {]Number currentMin = (i);int currentMinIndex = i;for (int j = i + 1; j < (); j++) { if () > (j).doubleValue()) { currentMin = (j); currentMinIndex = j;}}public class Exercise13_04 {static MyCalendar calendar = new MyCalendar();public static void main(String[] args) {int month = + 1;int year = ;if > 2)"Usage java Exercise13_04 month year");else if == 2) {etRadius())return 1;else if (getRadius() < ((Circle1) o).getRadius()) return -1;elsereturn 0;}}06public class Exercise13_06 {etArea());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) { = side;}@Overridepublic void howToColor() {"Color all four sides");}@Overridepublic double getArea() { return side * side;}@Overridepublic double getPerimeter() { return 4 * side;}}08import class Exercise13_08 {public static void main(String[] args) {MyStack1 stack = new MyStack1();("S1");("S2");("S");MyStack1 stack2 = (MyStack1) ()); ("S1");("S2");("S");class MyStack1 implements Cloneable {private ArrayList<Object> list = new ArrayList<Object>();public boolean isEmpty() {return ();public int getSize() {return ();}public Object peek() {return (getSize() - 1);}public Object pop() {Object o = (getSize() - 1);(getSize() - 1);return o;}public void push(Object o) {(o);}/** Override the toString in the Object class */ public String toString() {return "stack: " + ();}public Object clone() {try {MyStack1 c = (MyStack1) ();= (ArrayList<Object>) 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();}}adius;}}10public class Exercise13_10 {public static void main(String[] args) {Rectangle13_10 obj1 = new Rectangle13_10();Rectangle13_10 obj2 = new Rectangle13_10();}}etArea();}}11public class Exercise13_11 {public static void main(String[] args) {Octagon a1 = new Octagon(5);"Area is " + ());"Perimeter is " + ());Octagon a2 = (Octagon)());"Compare the methods " + (a2));}}class Octagon extends GeometricObject implements Comparable<Octagon>, Cloneable { private double side;/** Construct a Octagon with the default side */ public Octagon () { etArea();return sum;}}etNumerator() == 0)return true;elsereturn false;/**Override the intValue method*/ public int intValue() {/**@todo: implement this abstract method*/return (int)doubleValue();}/**Override the floatValue method*/ public float floatValue() {/**@todo: implement this abstract method*/return (float)doubleValue();}/**Override the doubleValue method*/ public double doubleValue() { /**@todo: implement this abstract method*/return r[0]*r[1];}/**Override the longValue method*/ public long longValue() {/**@todo: implement this abstract method*/return (long)doubleValue();}@Overridepublic int compareTo(NewRational o) {/**@todo: Implement this method*/if (((NewRational)o)).getNumerator() > 0) return 1;else if (((NewRational)o)).getNumerator() < 0) return -1;elsereturn 0;}}15import .*;public class Exercise13_15 {public static void main(String[] args) {Rational r1 = new Rational(new BigInteger("4"), new BigInteger("2"));Rational r2 = new Rational(new BigInteger("2"), new BigInteger("3"));ivide(gcd);else= (gcd);= ().divide(gcd);}/** Find GCD of two numbers */private static BigInteger gcd(BigInteger n, BigInteger d) { BigInteger n1 = ();BigInteger n2 = ();BigInteger gcd = ;for (BigInteger k = ;(n1) <= 0 && (n2) <= 0;k = ) {if (k).equals &&(k).equals)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 = ()).add(()));BigInteger d = ());return new Rational(n, d);/** Subtract a rational number from this rational */public Rational subtract(Rational secondRational) {BigInteger n = ()).subtract(()));BigInteger d = ()); return new Rational(n, d);}/** Multiply a rational number to this rational */ public Rational multiply(Rational secondRational) {BigInteger n = ());BigInteger d = ()); return new Rational(n, d);}/** Divide a rational number from this rational */ public Rationaldivide(Rational secondRational) {BigInteger n = ());BigInteger d = ; return new Rational(n, d);}@Override public String toString() {if )return numerator + "";elsereturn numerator + "/" + denominator;}@Override /** Override the equals method in the Object class */ public boolean equals(Object parm1) {if (((Rational)(parm1))).getNumerator().equals)return true;elsereturn false;}@Override /** Override the hashCode method in the Object class */ public int hashCode() {return new Double()).hashCode();}@Override /** Override the abstract intValue method in */ public int intValue() {return (int)doubleValue();}@Override /** Override the abstract floatValue method in */ public float floatValue() { return (float)doubleValue();}@Override /** Override the doubleValue method in */public double doubleValue() {return () / ();}@Override /** Override the abstract longValue method in */ public long longValue() { return (long)doubleValue();}@Overridepublic int compareTo(Rational o) {if (((Rational)o)).getNumerator()pareTo > 0) return 1;else if (((Rational)o)).getNumerator()pareTo < 0) return -1;elsereturn 0;}}}16public class Exercise13_16 {public static void main(String[] args) {Rational result = new Rational(0, 1);if != 1) {"Usage: java Exercise13_16 \"operand1 operator operand2\""); (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]));}+ " " + tokens[1] + " " + tokens[2] + " = " + result);}static Rational getRational(String s) {String[] st = ("/");int numer = (st[0]);int denom = (st[1]);return new Rational(numer, denom);}}/* Alternatively, you can use StringTokenizer. See Supplement on StringTokenizer as alternativeimport class Exercise15_18 {public static void main(String[] args) {Rational result = new Rational(0, 1);if != 3) {"Usage: java Exercise15_22 operand1 operator operand2");(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]));}+ " " + tokens[1] + " " + tokens[2] + " = " + result);}static Rational getRational(String s) {"(" + c1"(" + c1 "(" + c1 "(" + c1"|" + c1 + "| = " + ());StringTokenizer st = new StringTokenizer(s, "/"); int numer = newInteger()).intValue(); int denom = new Integer()).intValue(); return newRational(numer, denom);}}*/ 17import class Exercise13_17 {public static void main(String[] args) { Scanner input = new Scanner; "Enter the first complex number: "); double a = (); double b = ();Complex c1 = new Complex(a, b);"Enter the second complex number: "); double c = ();double d = ();Complex c2 = new Complex(c, d);+ ")" + " + " + "(" + c2 + ")" + " = " + (c2)); + ")" + " - " + "(" + c2 + ")" + " = " + (c2)); + ")" + " * " + "(" + c2 + ")" + " = " + (c2)); + ")" + " / " + "(" + c2 + ")" + " = " + (c2)); Complex c3 = (Complex)();== c3);}}class Complex implements Cloneable { private double a = 0, b = 0;public Complex() { }Complex(double a, double b) { = a;= b;public Complex(double a) {= a;}public double getA() {return a;}public double getB() {return b;}public Complex add(Complex secondComplex) { double newA = a + ();double newB = b + ();return new Complex(newA, newB);}public Complex subtract(Complex secondComplex) { double newA = a - (); double newB = b - ();return new Complex(newA, newB);}public Complex multiply(Complex secondComplex) { double newA = a * () - b * (); double newB = b * () + a * ();return new Complex(newA, newB);}public Complex divide(Complex secondComplex) { double newA = (a * () + b * ()) / (), + (),);double newB = (b * () - a * ())/ (), + (),);return new Complex(newA, newB);}public double abs() {return (a * a + b * b);+ items[1]), @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 inthe Object class */public Object clone() {");if == 1) {return new Rational(new BigInteger(items[0]), ;}else {Rational r = new Rational(new BigInteger(items[0]getDenominator(items[1].length()));return r;}}private static BigInteger getDenominator(int size) {BigInteger result = ;for (int i = 0; i < size; i++)result = (new BigInteger("10"));return result;}static class Rational extends Number implements Comparable<Rational>{ ivide(gcd);else = (gcd);= ().divide(gcd);/** Find GCD of two numbers */private static BigInteger gcd(BigInteger n, BigInteger d) { BigInteger n1 = (); BigInteger n2 = ();BigInteger gcd = ;for (BigInteger k = ;(n1) <= 0 && (n2) <= 0;k = ) {if (k).equals &&(k).equals)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 = ()).add(()));BigInteger d = ());return new Rational(n, d);}/** Subtract a rational number from this rational */ public Rational subtract(Rational secondRational) {BigInteger n = ()).subtract(()));BigInteger d = ());return new Rational(n, d);/** Multiply a rational number to this rational */public Rational multiply(Rational secondRational) {BigInteger n = ());BigInteger d = ());return new Rational(n, d);}/** Divide a rational number from this rational */public Rational divide(Rational secondRational) {BigInteger n = ());BigInteger d = ;return new Rational(n, d);}@Overridepublic String toString() {if )return numerator + "";elsereturn numerator + "/" + denominator;}@Override /** Override the equals method in the Object class */ public boolean equals(Object parm1) {if (((Rational)(parm1))).getNumerator().equals)return true;elsereturn false;}@Override /** Override the hashCode method in the Object class */ public int hashCode() {return new Double()).hashCode();}@Override /** Override the abstract intValue method in */ public int intValue() { return (int)doubleValue();}@Override /** Override the abstract floatValue method in */ public float floatValue() { return (float)doubleValue();@Override /** Override the doubleValue method in */public double doubleValue() {return () / ();}@Override /** Override the abstract longValue method in */ public long longValue() { return (long)doubleValue();}@Overridepublic int compareTo(Rational o) {if (((Rational)o)).getNumerator()pareTo > 0)return 1;else if (((Rational)o)).getNumerator()pareTo < 0)return -1;elsereturn 0;}}}20import class Exercise13_20 {public static void main(String[] args) {Scanner input = new Scanner;"Enter a, b, c: ");double a = ();double b = ();double c = ();double discriminant = b * b - 4 * a * c;if (discriminant < 0) {Complex r1 = new Complex(-b / (2 * a), (-discriminant, / (2 * a));Complex r2 = new Complex(-b / (2 * a), (-discriminant, / (2 * a)); "The roots are " + r1 + " and " + r2);}else if (discriminant == 0) {double r1 = -b / (2 * a);"The root is " + r1);}else { // (discriminant > 0)double r1 = (-b + (discriminant, ) / (2 * a); double r2 = (-b - (discriminant, ) / (2 * a);"The roots are " + r1 + " and " + r2);}}}21 import class Exercise13_21 { public static void main(String[] args) { Scanner input = new Scanner;"Enter a, b, c: "); int a = ();int b = (); int c = ();Rational h = new Rational(-b, 2 * a);Rational k = new Rational(4 * a * c - b * b, 4 * a);"h is " + h + " " + "k is " + k); }。
(完整版)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);}}。
java语言程序设计基础篇第十版第五章
java语言程序设计基础篇第十版第五章摘要:一、Java 语言程序设计基础篇第十版第五章概述二、Java 程序设计基本概念与技术三、面向对象程序设计四、Java 程序设计高级主题五、Java 语言程序设计基础篇第十版第五章知识点详解六、Java 语言程序设计基础篇第十版第五章课后答案与练习题正文:一、Java 语言程序设计基础篇第十版第五章概述本章节主要介绍了Java 语言程序设计的基础知识,包括基本程序设计、语言结构、面向对象程序设计、继承与多态等内容。
通过学习本章节,读者可以掌握Java 语言的基本语法和编程技巧,为后续的学习打下坚实的基础。
二、Java 程序设计基本概念与技术1.基本数据类型:Java 语言中常用的基本数据类型包括整型、浮点型、布尔型和字符型等。
2.控制结构:Java 语言中的控制结构包括条件语句(如if-else)、循环语句(如for、while 和do-while)以及分支语句(如switch)等。
3.函数与方法:Java 语言中的函数称为方法,它可以实现代码的封装和重用。
方法的调用方式包括直接调用、间接调用和链式调用等。
4.数组:Java 语言中的数组是一种用于存储多个相同类型数据的集合。
数组可以进行遍历、排序等操作。
5.面向对象程序设计:Java 语言是一种面向对象的编程语言,它支持类和对象的概念。
类是一种抽象的数据类型,包含属性和方法;对象是类的实例,通过创建对象,可以调用类中定义的方法来实现具体的功能。
三、面向对象程序设计1.类与对象:Java 语言中的面向对象程序设计主要通过类和对象来实现。
类是一种抽象的数据类型,包含属性和方法;对象是类的实例,通过创建对象,可以调用类中定义的方法来实现具体的功能。
2.继承与多态:继承是Java 语言中实现代码重用的一种方式,它允许一个类(子类)继承另一个类(父类)的属性和方法。
多态是Java 语言中实现面向对象程序设计的重要特性之一,它允许一个接口或抽象类有多种实现方式。
Java语言程序设计(基础篇)(第10版 梁勇著)第二章练习题答案
《Java语言程序设计(基础篇)》(第10版 梁勇 著) 第二章 基本程序设计 练习题答案
本人在自学编程过程中,发现本书答案很难找,找到的要么不完整、要么错误百出,所以我将自己所做的 练习题答案,提供给有需要者,供大家交流。本章答案均为本人一字一字所敲,答案均经过验证,虽为初学者, 但代码均按照书中规范要求书写,如有错误或更好的建议,请指正交流。
// 第二章 P59 练习题2.1 (将摄氏温度转为华氏温度) import java.util.Scanner;
public class CelsiusToFahrenheit {
public static void main(String[] args) { // 华氏温度和摄氏温度的转换公式为:华氏温度 = (9/5)*摄氏温度+32 Scanner input = new Scanner(System.in);
System.out.print("Enter the time zone offset to GMT: "); long timeZoneOffset = input.nextLong(); // 此处用long还是int?
long totalMilliseconds = System.currentTimeMillis(); long totalSeconds = totalMilliseconds / 1000; long currentSecond = totalSeconds % 60; long totalMinutes = totalSeconds / 60; long currentMinute = totalMinutes % 60; long totalHours = totalMinutes / 60; long currentHour = totalHours % 24; long hour = currentHour + timeZoneOffset;
《Java语言程序设计(基础篇)》(第10版 梁勇 著)第二十一章练习题答案
《Java语言程序设计(基础篇)》(第10版梁勇著)第二十一章练习题答案21.1import java.util.*;public class Exercise21_01 {public static void main(String[] args) {LinkedHashSet<String> set1 = new LinkedHashSet<String>(Arrays.asList( new String[]{"George", "Jim", "John", "Blake", "Kevin", "Michael"}));LinkedHashSet<String> set1Clone1 = (LinkedHashSet<String>)set1.clone(); LinkedHashSet<String> set1Clone2 = (LinkedHashSet<String>)set1.clone();LinkedHashSet<String> set2 = new LinkedHashSet<String>(Arrays.asList( new String[] {"George", "Katie", "Kevin", "Michelle", "Ryan"}));set1.addAll(set2);set1Clone1.removeAll(set2);set1Clone2.retainAll(set2);System.out.println("The union of the two sets is " + set1);System.out.println("The difference of the two sets is " + set1Clone1); System.out.println("The intersection of the two sets is " + set1Clone2); }}21.1附加import java.util.*;public class Exercise21_01Extra {public static void main(String[] args) {System.out.print("Enter a string: ");Scanner input = new Scanner(System.in);String s = input.nextLine();Character[] list1 = {'A', 'E', 'I', 'O', 'U'};Set<Character> vowels = new HashSet<>(Arrays.asList(list1));Set<Character> vowelsInString = new HashSet<>();Set<Character> consonantsInString = new HashSet<>();int numbeOfVowels = 0;int numbeOfConsonants = 0;for (int i = 0; i < s.length(); i++) {char ch = Character.toUpperCase(s.charAt(i));if (Character.isLetter(ch)) {if (vowels.contains(ch)) {if (!vowelsInString.contains(ch)) {vowelsInString.add(ch);numbeOfVowels++;}}else if (!consonantsInString.contains(ch)) {consonantsInString.add(ch);numbeOfConsonants++;}}}System.out.println("The number of vowels is " + numbeOfVowels);System.out.println("The number of consonants is " + numbeOfConsonants); }}21.2import java.util.*;import java.io.*;public class Exercise21_02 {public static void main(String[] args) {if (args.length != 1) {System.out.println("Usage: java Exercise21_02 fullfilename");System.exit(1);}String filename = args[0];// Create a tree set to hold the wordsTreeSet<String> treeSet = new TreeSet<String>();try {Scanner in = new Scanner(new File(filename));String line;while ((line = in.nextLine()) != null) {String[] tokens = line.split("[ |\n|\t|\r|.|,|)|(|-|\"]");for (int i = 0; i < tokens.length; i++)treeSet.add(tokens[i]);}}catch (Exception ex) {System.err.println(ex);}// Get an iterator for the setIterator iterator = treeSet.iterator();// Display mappingsSystem.out.println("\nDisplay words in ascending order ");while (iterator.hasNext()) {System.out.println(iterator.next());}}}21.3import java.util.*;import java.io.*;public class Exercise21_03 {public static void main(String[] args) {// Check usageif (args.length != 1) {System.out.println("Usage: java Exercise21_03 file.java");System.exit(1);}// Array of all Java keywords + true + nullString[] keywordString = {"abstract", "finally", "public", "boolean", "float", "return", "break", "for", "short", "byte","goto", "static", "case", "if", "super", "catch", "implements", "switch", "char", "import", "synchronized", "class","instanceof", "this", "const", "int", "throw", "continue","interface", "throws", "default", "long", "transient", "do","native", "try", "double", "new", "void", "else", "package","volatile", "extends", "private", "while", "final","protected", "true", "null"};Set<String> keywordSet =new HashSet<String>(Arrays.asList(keywordString));int count = 0;try {Scanner input = new Scanner(new File(args[0]));String text = "";while (input.hasNext()) {String line = input.nextLine();line = stripLineComments(line);line = stripLineStringLiterals(line);text += line + " ";}text = stripParagraghComments(text);String[] tokens = text.split("[ \\[,()\\]]");for (String token: tokens) {if (keywordSet.contains(token))count++;}System.out.println("The number of keywords in the program is " + count);}catch (Exception ex) {ex.printStackTrace();}}/* Strip line comments */private static String stripLineComments(String line) {int index = line.indexOf("//");if (index < 0)return line;elsereturn line.substring(0, index);}/* Strip string literals */private static String stripLineStringLiterals(String line) {int start = line.indexOf("\"");int end = line.indexOf("\"", start + 1);while (start > 0 && end > 0) {line = line.substring(0, start) + line.substring(end + 1);start = line.indexOf("\"");end = line.indexOf("\"");}return line;}/* Strip paragraph comments */private static String stripParagraghComments(String text) {int start = text.indexOf("/*");int end = text.indexOf("*/");while (start > 0 && end > 0) {text = text.substring(0, start) + text.substring(end + 2);start = text.indexOf("/*");end = text.indexOf("*/");}return text;}}/** This is an incorrect version. It does not count the case such as (this. Here the this keyword* is not counted. It does not exclude keywords in the comments*import java.util.*;import java.io.*;public class Exercise20_03 {public static void main(String[] args) {// Check usageif (args.length != 1) {System.out.println("Usage: java Exercise20_03 file.java");System.exit(0);}// Array of all Java keywords + true + nullString[] keywordString = {"abstract", "finally", "public","boolean", "float", "return", "break", "for", "short", "byte", "goto", "static", "case", "if", "super", "catch", "implements", "switch", "char", "import", "synchronized", "class","instanceof", "this", "const", "int", "throw", "continue","interface", "throws", "default", "long", "transient", "do","native", "try", "double", "new", "void", "else", "package","volatile", "extends", "private", "while", "final","protected", "true", "null"};Set<String> keywordSet =new HashSet<String>(Arrays.asList(keywordString));int count = 0;try {Scanner input = new Scanner(new File(args[0]));while (input.hasNext()) {String token = input.next();if (keywordSet.contains(token))count++;}System.out.println("The number of keywords in the program is " + count);}catch (Exception ex) {ex.printStackTrace();}}}*/21.4import java.util.Scanner;import java.util.HashSet;import java.util.Arrays;public class Exercise21_04 {public static void main(String[] args) throws Exception {HashSet<Character> set1 = new HashSet<Character>(Arrays.asList( new Character[]{'A', 'E', 'I', 'O', 'U'}));System.out.print("Enter a filename: ");Scanner input = new Scanner(System.in);String filename = input.nextLine();input = new Scanner(new java.io.File(filename));int countVowels = 0;int countConsonants = 0;while (input.hasNext()) {String s = input.nextLine().toUpperCase();for (int i = 0; i < s.length(); i++) {if (set1.contains(s.charAt(i)))countVowels++;else if (Character.isLetter(s.charAt(i)))countConsonants++;}}System.out.println("The number of vowels is " + countVowels + " and consonanats is " +countConsonants);}}21.5/*** Usage: Copy this class to the folder, run it with java JavaToHTMLftim * to generate* HTM file for all the .java file in this folder. The generated .htm files are* stored in the same folder*/import java.util.*;import java.io.*;public class Exercise21_05 {// Array of all Java keywords + true + false + nullstatic String[] keywordString = {"abstract", "assert", "boolean","break", "byte", "case", "catch", "char", "class", "const","continue", "default", "do", "double", "else", "enum","extends", "for", "final", "finally", "float", "goto", "if","implements", "import", "instanceof", "int", "interface","long", "native", "new", "package", "private", "protected","public", "return", "short", "static", "strictfp", "super","switch", "synchronized", "this", "throw", "throws","transient", "try", "void", "volatile", "while","true", "false", "null"};static Set<String> keywordSet =new HashSet<String>(Arrays.asList(keywordString));/** Main method */public static void main(String[] args) throws Exception {// Check usageif (args.length != 2) {System.out.println("Usage: java Exercise20_10 javaSourcefile htmlfile");System.exit(1);}Scanner input = new Scanner(new File(args[0]));PrintWriter output = new PrintWriter(new File(args[1]));JavaToHTML(input, output);}static boolean stringToken = false;static String inputFileName;public static void JavaToHTML(Scanner input, PrintWriter output) { try {output.format("%s\r\n", "<html>");output.format("%s\r\n", "<head>");output.format("%s\r\n","<title>Intro to Java Programming, 6E - " + inputFileName +"</title>");output.format("%s\r\n","<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">");output.format("%s\r\n", "<style type = \"text/css\">");output.format("%s\r\n","body {font-family: \"Courier New\", sans-serif; font-size: 100%; color: black}");output.format("%s\r\n",".keyword {color: #000080; font-weight: bold}");output.format("%s\r\n", ".comment {color: #008000}");output.format("%s\r\n", ".literal {color: #0000ff}");// Match the color in the text// output.format("%s\r\n", ".keyword {color: black; font-weight: bold}");// output.format("%s\r\n", ".comment {color: #77797C}");// output.format("%s\r\n", ".literal {color: #007346; font-weight: bold}");output.format("%s\r\n", "</style>");output.format("%s\r\n", "</head>");output.format("%s\r\n", "<body>");output.format("%s\r\n", "<pre>");String text = "";String temp;// Read all lineswhile (input.hasNext()) {temp = input.nextLine();text += temp + "\r\n";}text = text.replaceAll(">", ">");text = text.replaceAll("<", "<");translateToHTML(text, input, output);output.format("%s\r\n", "</pre>");output.format("%s\r\n", "</body>");output.format("%s\r\n", "</html>");}catch (Exception ex) {System.out.println(ex);}finally {try {input.close();output.close();}catch (Exception ex) {}}}/** Translate Java source code to HTML */static void translateToHTML(String text, Scanner input, PrintWriter output) throws Exception {text = text.replaceAll("// ", "LINECOMMENT");text = text.replaceAll("/\\*", "BLOCKCOMMENT");String token;while (text != null && text.length() > 0) {// * and / are in conflict with /* and //String[] parts = text.split("[%\\+\\-\\*/\r\n\t \\[\\].;(){},]", 2); token = parts[0];if (token.length() > 1 && token.startsWith("LINECOMMENT")) {output.format("%s", "<span class = \"comment\">");parts = text.split("\r\n", 2);text = parts[1];output.format("%s", parts[0].replaceAll("LINECOMMENT", "// "));output.format("%s", "</span>\r\n");continue;}else if (token.length() > 1 && token.startsWith("BLOCKCOMMENT")) {output.format("%s", "<span class = \"comment\">");parts = text.split("\\*/", 2);text = parts[1];output.format("%s", parts[0].replaceAll("BLOCKCOMMENT", "/*") +"*/");output.format("%s", "</span>");continue;}else if (token.length() > 1 && token.matches("'\\w'*")) {output.format("%s", "<span class = \"literal\">");output.format("%s", token);output.format("%s", "</span>");}else if (token.startsWith("\"") && token.endsWith("\"") &&(token.length() > 1)) {output.format("%s", "<span class = \"literal\">" + token+ "</span>");}else if (token.startsWith("'") && token.endsWith("'") &&(token.length() > 1)) {output.format("%s", "<span class = \"literal\">" + token+ "</span>");}else if (token.equals("' '")) {output.format("%s", "<span class = \"literal\">" + token+ "</span>");}else if (token.startsWith("\"") && token.endsWith("\"") &&(token.length() == 1)) {if (stringToken) {output.format("%s", token + "</span>");stringToken = false;}else {output.format("%s", "<span class = \"literal\">" + token); stringToken = true;}}else if (token.startsWith("\"")) {output.format("%s", "<span class = \"literal\">" + token); stringToken = true;}else if (token.endsWith("\"") && (!token.endsWith("\\\""))) { output.format("%s", token);output.format("%s", "</span>");stringToken = false;}else if (token.matches("\\d+")) { // Check if numericoutput.format("%s", "<span class = \"literal\">" + token +"</span>");}else if (!stringToken && keywordSet.contains(token)) {output.format("%s", "<span class = \"keyword\">" + token +"</span>");}else {output.format("%s", token);}if (token.length() < text.length()) {if (text.charAt(token.length()) == '<')output.format("%s", "<");else if (text.charAt(token.length()) == '>')output.format("%s", ">");elseoutput.format("%s", text.charAt(token.length()));}if (parts.length == 2) {text = parts[1];}}}}21.6import java.util.*;public class Exercise21_06 {public static void main(String[] args) {// Create a tree map to hold words and key and count as value TreeMap<Integer, Integer> treeMap = new TreeMap<>();Scanner input = new Scanner(System.in);while (true) {// Enter an integerSystem.out.print("Enter an integer: ");int number = input.nextInt();if (number == 0) break;Integer key = new Integer(number);if (treeMap.get(key) != null) {int value = ((Integer)treeMap.get(key)).intValue();value++;treeMap.put(key, new Integer(value));}else {treeMap.put(key, new Integer(1));}}Integer max = Collections.max(treeMap.values());Set<Integer> keys = treeMap.keySet();Iterator<Integer> iterator = keys.iterator();while (iterator.hasNext()) {Object key = iterator.next();Integer value = (Integer)(treeMap.get(key));if (value.equals(max)) {System.out.println("Number " + key + " occurred most");}}}}21.7import java.util.*;public class Exercise21_07 {public static void main(String[] args) {// Text in a stringString text = "Have a good day. Have a good class. " + "Have a good visit. Have fun!";// Create a hash map to hold words and key and count as value HashMap<String, Integer> hashMap = new HashMap<>();String[] tokens = text.split("[ |.|!|?]");for (String key: tokens) {if (hashMap.get(key) != null) {hashMap.put(key, hashMap.get(key).intValue() + 1);}else {if (key.trim().length() > 0)hashMap.put(key, 1);}}// Get an entry set for the tree mapSet<Map.Entry<String, Integer>> entrySet = hashMap.entrySet();ArrayList<WordOccurrence> list = new ArrayList<>();for (Map.Entry<String, Integer> entry: entrySet) {list.add(new WordOccurrence(entry.getKey(), entry.getValue())); }Collections.sort(list);for (WordOccurrence item: list) {System.out.println(item);}}}class WordOccurrence implements Comparable<WordOccurrence> {String word;int count;public WordOccurrence(String word, int count) {this.word = word;this.count = count;}@Overridepublic int compareTo(WordOccurrence o) {return count - o.count;}@Overridepublic boolean equals(Object o) {return word.equals(((WordOccurrence)o).word);}@Overridepublic String toString() {return word + ": " + count;}}21.8import java.util.*;import java.io.*;public class Exercise21_08 {public static void main(String[] args) {if (args.length != 1) {System.out.println("Usage: java Exercise21_08 fullfilename");System.exit(1);}String filename = args[0];// Create a tree map to hold words as key and count as valueTreeMap<String, Integer> treeMap = new TreeMap<String, Integer>();try {Scanner input = new Scanner(new File(filename));while (input.hasNext()) {String line = input.nextLine();String[] words = line.split("[ @!~{}\\[\\]$#^&*\n\t\r.,;?'\")(]");for (int i = 0; i < words.length; i++) {if (words[i].trim().length() > 0 &&words[i].trim().matches("[A-Z|a-z]+")) {String key = words[i].toLowerCase();if (treeMap.get(key) != null) {int count = treeMap.get(key);count++;treeMap.put(key, count);}else {treeMap.put(key, 1);}}}}}catch (Exception ex) {ex.printStackTrace();}// Get an entry set for the tree mapSet<Map.Entry<String, Integer>> entrySet = treeMap.entrySet();// Display words in alphabetical orderSystem.out.println("\nDisplay words and their count in " + " ascending order of the words");for (Map.Entry<String, Integer> entry: entrySet)System.out.println(entry.getValue() + "\t" + entry.getKey()); }}21.9import java.util.*;public class Exercise21_09 {public static void main(String[] args) {String[][] stateCapital = {{"Alabama", "Montgomery"},{"Alaska", "Juneau"},{"Arizona", "Phoenix"},{"Arkansas", "Little Rock"},{"California", "Sacramento"},{"Colorado", "Denver"},{"Connecticut", "Hartford"},{"Delaware", "Dover"},{"Florida", "Tallahassee"},{"Georgia", "Atlanta"},{"Hawaii", "Honolulu"},{"Idaho", "Boise"},{"Illinois", "Springfield"},{"Indiana", "Indianapolis"},{"Iowa", "Des Moines"},{"Kansas", "Topeka"},{"Kentucky", "Frankfort"},{"Louisiana", "Baton Rouge"},{"Maine", "Augusta"},{"Maryland", "Annapolis"},{"Massachusettes", "Boston"},{"Michigan", "Lansing"},{"Minnesota", "Saint Paul"},{"Mississippi", "Jackson"},{"Missouri", "Jefferson City"},{"Montana", "Helena"},{"Nebraska", "Lincoln"},{"Nevada", "Carson City"},{"New Hampshire", "Concord"},{"New Jersey", "Trenton"},{"New York", "Albany"},{"New Mexico", "Santa Fe"},{"North Carolina", "Raleigh"},{"North Dakota", "Bismark"},{"Ohio", "Columbus"},{"Oklahoma", "Oklahoma City"},{"Oregon", "Salem"},{"Pennslyvania", "Harrisburg"},{"Rhode Island", "Providence"},{"South Carolina", "Columbia"},{"South Dakota", "Pierre"},{"Tennessee", "Nashville"},{"Texas", "Austin"},{"Utah", "Salt Lake City"},{"Vermont", "Montpelier"},{"Virginia", "Richmond"},{"Washington", "Olympia"},{"West Virginia", "Charleston"},{"Wisconsin", "Madison"},{"Wyoming", "Cheyenne"}};Map<String, String> map = new HashMap<String, String>();for (int i = 0; i < stateCapital.length; i++)map.put(stateCapital[i][0].toLowerCase(), stateCapital[i][1]);Scanner input = new Scanner(System.in);System.out.print("Enter a state: ");String state = input.nextLine().toLowerCase().trim();if (map.containsKey(state))System.out.println("The capital is " +map.get(state));elseSystem.out.println("No such state ");}}21.10import java.util.*;import java.io.*;public class Exercise21_10 {public static void main(String[] args) {// Prompt the user to enter a Java source fileScanner input = new Scanner(System.in);System.out.print("Enter a file name: ");String filename = input.nextLine();// Array of all Java keywords + true + nullString[] keywordString = { "abstract", "finally", "public", "boolean", "float", "return", "break", "for", "short", "byte", "goto", "static","case", "if", "super", "catch", "implements", "switch", "char","import", "synchronized", "class", "instanceof", "this", "const","int", "throw", "continue", "interface", "throws", "default", "long","transient", "do", "native", "try", "double", "new", "void", "else","package", "volatile", "extends", "private", "while", "final","protected", "true", "null" };Set<String> keywordSet = newHashSet<String>(Arrays.asList(keywordString));int count = 0;try {input = new Scanner(new File(filename));String text = "";while (input.hasNext()) {String line = input.nextLine();line = stripLineComments(line);line = stripLineStringLiterals(line);text += line + " ";}text = stripParagraghComments(text);TreeMap<String, Integer> map = new TreeMap<String, Integer>();String[] tokens = text.split("[ \\[,()\\]]");for (String token : tokens) {if (keywordSet.contains(token))if (map.get(token) == null) {map.put(token, 1);} else {int value = map.get(token);value++;map.put(token, value);}}// Get all entries into a setSet<Map.Entry<String, Integer>> entrySet = map.entrySet();// Get key and value from each entryfor (Map.Entry<String, Integer> entry: entrySet)System.out.println(entry.getValue() + "\t" + entry.getKey()); } catch (Exception ex) {ex.printStackTrace();}}/* Strip line comments */private static String stripLineComments(String line) {int index = line.indexOf("//");if (index < 0)return line;elsereturn line.substring(0, index);}/* Strip string literals */private static String stripLineStringLiterals(String line) {int start = line.indexOf("\"");int end = line.indexOf("\"", start + 1);while (start > 0 && end > 0) {line = line.substring(0, start) + line.substring(end + 1);start = line.indexOf("\"");end = line.indexOf("\"");}return line;}/* Strip paragraph comments */private static String stripParagraghComments(String text) {int start = text.indexOf("/*");int end = text.indexOf("*/");while (start > 0 && end > 0) {text = text.substring(0, start) + text.substring(end + 2);start = text.indexOf("/*");。
《Java语言程序设计-基础篇》答案-第10章
10.6 答:正确。
网
案
答
后
课
1/3 = 0.3333333333333333 1/2 = 0.5
10.4 答:错误如下:
(1)找不到符号
符号: 方法 add(Rational)
位置: 类 ng.Number
System.out.println(r.add(new Rational())); (2)找不到符号
om 符号: 方法 add(Rational) .c 位置: 类 ng.Number w System.out.println((Rational)r.add(new Rational())); khda 10.5 答:错误原因:ng.Number 是抽象的;无法对其进行实例化 www. Number r = new Number();
网(继承)
(组合)
案 账户和存款账户 (继承)
答
后 10.3 答:输出结果如下:
课1/3 + 1/2 = 5/6
1/2 + 1/3 = 5/6
1/3 - 1/2 = -1/6
1/2 - 1/3 = 1/6
1/3 * 1/2 = 1/6
1/2 * 1/3 = 1/9
1/31/3 = 3/2
绘图略公司和雇员聚集课程和师资关联学生和人继承房子和窗户组合账户和存款账户继承103答
第 10 章 面向对象建模
复习题
10.1 答:
类之间的关系
图形符号
继承
关联 聚集 组合(包容) 依赖
10.2 答:绘图略 公司和雇员 课程和师资
((聚关集联))
学生和人 房子和窗户
《Java语言程序设计(基础篇)》(第10版梁勇著)第三章练习题答案
《Java语言程序设计(基础篇)》(第10版梁勇著)第三章练习题答案《Java语言程序设计(基础篇)》(第10版梁勇著)第三章练习题答案3.1public class Exercise03_01 {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) {System.out.println("The equation has no real roots");}else if (discriminant == 0) {double r1 = -b / (2 * a);System.out.println("The equation has one root " + 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 equation has two roots " + r1 + " and " + r2);}}}3.1附加public class Exercise03_01Extra {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter a numerator: ");int numerator = input.nextInt();System.out.print("Enter a denominator: ");int denominator = input.nextInt();if (numerator < denominator) {System.out.println(numerator + " / " + denominator + " is a proper fraction");}else if (numerator % denominator == 0) {System.out.print(numerator + " / " + denominator + " is an improper fraction ");System.out.println("and it can be reduced to " + numerator / denominator);}else {System.out.print(numerator + " / " + denominator + " is an improper fraction ");System.out.println("and its mixed fraction is " + numerator / denominator + " + " +numerator % denominator + " / " + denominator);}}}3.2public class Exercise03_02 {public static void main(String[] args) {Scanner input = new Scanner(System.in);int number1 = (int)(System.currentTimeMillis() % 10);int number2 = (int)(System.currentTimeMillis() * 7 % 10);int number3 = (int)(System.currentTimeMillis() * 3 % 10);System.out.print("What is " + number1 + " + " + number2 + " + " +number3 + "? ");int answer = input.nextInt();System.out.println(number1 + " + " + number2 + " + " + number3 +" = " + answer + " is " +(number1 + number2 + number3 == answer));}}3.2附加public class Exercise03_02Extra {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter the coordinates for two points: ");double x1 = input.nextDouble();double y1 = input.nextDouble();double x2 = input.nextDouble();double y2 = input.nextDouble();double m = (y2 - y1) / (x2 - x1);double b = y1 - m * x1;System.out.print("The line equation for two points (" + x1 + ", " + y1 + ") and (" + x2 + ", " + y2 + ") is " + "y = ");if (m == -1)System.out.print("-x");else if (m == 1)System.out.print("x");elseSystem.out.print(m + "x");if (b > 0)System.out.println(" + " + b);else if (b < 0)System.out.println(" - " + (-1 * b));else// b is 0System.out.println();}}3.3public class Exercise03_03 {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();double detA = a * d - b * c;if (detA == 0) {System.out.println("The equation has no solution"); }else {double x = (e * d - b * f) / detA;double y = (a * f- e * c) / detA;System.out.println("x is " + x + " and y is " + y);}}}3.3附加public class Exercise03_03Extra {public static void main(String[] args) {final double RADIUS = 5;double angle = Math.random() * 2 * Math.PI;double x = RADIUS * Math.random() * Math.cos(angle);double y = RADIUS * Math.sin(angle);double distance = Math.pow(x * x + y * y, 0.5);System.out.println("The point is (" + x + ", " + y + ") and its distance to the center is " + distance);}}3.4public class Exercise03_04 {public static void main(String[] args) {int number = (int)(Math.random() * 12) + 1;// or int number = (int)(System.currentTimeMillis() % 12 + 1);// or int number = (int)(Math.random() * 12) + 1;if (number == 1)System.out.println("Month is Januaray");else if (number == 2)System.out.println("Month is Feburary");else if (number == 3)System.out.println("Month is March");else if (number == 4)System.out.println("Month is April");else if (number == 5)System.out.println("Month is May");else if (number == 6)System.out.println("Month is June");else if (number == 7)System.out.println("Month is July");else if (number == 8)System.out.println("Month is August");else if (number == 9)System.out.println("Month is September");else if (number == 10)System.out.println("Month is October");else if (number == 11)System.out.println("Month is November");else// if (number == 12)System.out.println("Month is December");}}3.5public class Exercise03_05 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter an integer for todaySystem.out.print("Enter today抯 day: ");int today = input.nextInt();System.out.print("Enter the number of days elapsed since today: ");int elapsedDays = input.nextInt();String nameForToday;if (today == 0)nameForToday = "Sunday";else if (today == 1)nameForToday = "Monday";else if (today == 2)nameForToday = "Tuesday";else if (today == 3)nameForToday = "Wednesday";else if (today == 4)nameForToday = "Thursday";else if (today == 5)nameForToday = "Friday";else// if (today == 6)nameForToday = "Saturday";int futureDay = (today + elapsedDays) % 7; String nameForFutureDay;if (futureDay == 0)nameForFutureDay = "Sunday";else if (futureDay == 1) nameForFutureDay = "Monday";else if (futureDay == 2) nameForFutureDay = "Tuesday";else if (futureDay == 3) nameForFutureDay = "Wednesday";else if (futureDay == 4) nameForFutureDay = "Thursday";else if (futureDay == 5) nameForFutureDay = "Friday";else// if (futureDay == 6) nameForFutureDay = "Saturday";System.out.println("Today is " + nameForToday+ " and the future day is " + nameForFutureDay); } }3.6public class Exercise03_06 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter weight in pounds System.out.print("Enter weight in pounds: "); double weight = input.nextDouble();// Prompt the user to enter heightSystem.out.print("Enter feet: ");double feet = input.nextDouble();System.out.print("Enter inches: ");double inches = input.nextDouble();double height = feet * 12 + inches;// Compute BMIdouble bmi = weight * 0.45359237 / ((height * 0.0254) * (height * 0.0254));// Display resultSystem.out.println("BMI is " + bmi);if (bmi < 18.5)System.out.println("Underweight");else if (bmi < 25)System.out.println("Normal");else if (bmi < 30)System.out.println("Overweight");elseSystem.out.println("Obese");}}3.7/** Break down an amount into smaller units* Display the non-zero denominations only, and display singular* words for single units like 1 dollars, 1 penny, and display plural * words for more than one unit like 2 dollars, 3 pennies.*/public class Exercise03_07 {// Main methodpublic static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Receive the amount entered from the keyboardSystem.out.print("Enter an amount in double, for example 11.56: ");double amount = input.nextDouble();int remainingAmount = (int)(amount * 100);// Find the number of one dollarsint numberOfOneDollars = remainingAmount / 100;remainingAmount = remainingAmount % 100;// Find the number of quarters in the remaining amountint numberOfQuarters = remainingAmount / 25;remainingAmount = remainingAmount % 25;// Find the number of dimes in the remaining amountint numberOfDimes = remainingAmount / 10;remainingAmount = remainingAmount % 10;// Find the number of nickels in the remaining amountint numberOfNickels = remainingAmount / 5;remainingAmount = remainingAmount % 5;// Find the number of pennies in the remaining amountint numberOfPennies = remainingAmount;// Display resultsif (amount < 0) {System.out.println("Your amount is negative");System.exit(1);}else if (amount < 0) {System.out.println("Your amount is zero");System.exit(2);}System.out.println("Your amount " + amount + " consists of ");if (numberOfOneDollars > 1)System.out.println(numberOfOneDollars + "\ dollars");else if (numberOfOneDollars == 1)System.out.println(numberOfOneDollars + "\ dollar");if (numberOfQuarters > 1)System.out.println(numberOfQuarters + "\ quarters");else if (numberOfQuarters == 1)System.out.println(numberOfQuarters + "\ quarter");if (numberOfDimes > 1)System.out.println(numberOfDimes + "\ dimes");else if (numberOfDimes == 1)System.out.println(numberOfDimes + "\ dime");if (numberOfNickels > 1)System.out.println(numberOfNickels + "\ nickels");else if (numberOfNickels == 1)System.out.println(numberOfNickels + "\ nickel");if (numberOfPennies > 1)System.out.println(numberOfPennies + "\ pennies");else if (numberOfPennies == 1)System.out.println(numberOfPennies + "\ penny");}}3.8public class Exercise03_08 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in); // Enter three numbersSystem.out.print("Enter three integers: ");int number1 = input.nextInt();int number2 = input.nextInt();int number3 = input.nextInt();if (number1 > number2) {int temp = number1;number1 = number2;number2 = temp;}if (number2 > number3) {int temp = number2;number2 = number3;number3 = temp;}if (number1 > number2) {int temp = number1;number1 = number2;number2 = temp;}System.out.println("The sorted numbers are "+ number1 + " " + number2 + " " + number3);}}public class Exercise03_09 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter an integerSystem.out.print("Enter the first 9 digits of an ISBN as integer: ");int number = input.nextInt();// Calculate checksum (You may write a loop to simplify it in Ch4int checksum =((number / 100000000 % 10) * 1 +(number / 10000000 % 10) * 2 +(number / 1000000 % 10) * 3 +(number / 100000 % 10) * 4 +(number / 10000 % 10) * 5 +(number / 1000 % 10) * 6 +(number / 100 % 10) * 7 +(number / 10 % 10) * 8 +(number % 10) * 9) % 11;System.out.print("The ISBN-10 number is ");// Display leading zeros, improve the solution using loops in the next chapterif (number / 100000000 == 0) {System.out.print("0");if (number / 10000000 == 0) {System.out.print("0");if (number / 1000000 == 0) {System.out.print("0");if (number / 100000 == 0) {System.out.print("0");if (number / 10000 == 0) { System.out.print("0");if (number / 1000 == 0) { System.out.print("0");if (number / 100 == 0) {System.out.print("0");if (number / 10 == 0) {System.out.print("0");if (number == 0) {System.out.print("0");}}}}}}}}}System.out.print(number);if (checksum == 10)System.out.print("X");elseSystem.out.print(checksum);}}3.10public class Exercise03_10 {public static void main(String[] args) {// 1. Generate two random single-digit integersint number1 = (int)(Math.random() * 10);int number2 = (int)(Math.random() * 10);// 2. Prompt the student to answer 搘hat is number1 + number2?? System.out.print("What is " + number1 + " + " + number2 + "? "); Scanner input = new Scanner(System.in);int answer = input.nextInt();// 4. Grade the answer and display the resultString replyString;if (number1 + number2 == answer)replyString = "You are correct!";elsereplyString = "Your answer is wrong.\" + number1 + " + "+ number2 + " should be " + (number1 + number2);System.out.println(replyString);}}3.11public class Exercise03_11 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter inputSystem.out.print("Enter a month in the year (e.g., 1 for Jan): ");int month = input.nextInt();System.out.print("Enter a year: ");int year = input.nextInt();int numberOfDaysInMonth = 0;switch (month) {case 1:System.out.print("January " + year);numberOfDaysInMonth = 31;break;case 2:System.out.print("February " + year);if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) { numberOfDaysInMonth = 29;}else {numberOfDaysInMonth = 28;}break;case 3:System.out.print("March " + year);numberOfDaysInMonth = 31;break;case 4:System.out.print("April " + year);numberOfDaysInMonth = 30;break;case 5:System.out.print("May " + year);numberOfDaysInMonth = 31;break;case 6:System.out.print("June " + year);numberOfDaysInMonth = 30;break;case 7:System.out.print("July " + year);numberOfDaysInMonth = 31;break;case 8:System.out.print("August " + year);numberOfDaysInMonth = 31;break;case 9:System.out.print("September " + year);numberOfDaysInMonth = 30;break;case 10:System.out.print("October " + year);numberOfDaysInMonth = 31;break;case 11:System.out.print("November " + year);numberOfDaysInMonth = 30;break;case 12:System.out.print("December " + year);numberOfDaysInMonth = 31;break;}System.out.print(" has " + numberOfDaysInMonth + " days"); }}3.12public class Exercise03_12 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a three-digit integer: ");int number = input.nextInt();if (number / 100 == number % 10)System.out.println(number + " is a palindrome");elseSystem.out.println(number + " is not a palindrome");}}3.13public class Exercise03_13 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter filing statusSystem.out.print("(0-single filer, 1-married jointly or qualifying widow(er),"+ "\2-married separately, 3-head of household)\" + "Enter the filing status: ");int status = input.nextInt();// Prompt the user to enter taxable incomeSystem.out.print("Enter the taxable income: ");double income = input.nextDouble();// Compute taxdouble tax = 0;if (status == 0) { // Compute tax for single filersif (income <= 8350) {tax = income * 0.10;} else if (income <= 33950) {tax = 8350 * 0.10 + (income - 8350) * 0.15;} else if (income <= 82250) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950)* 0.25; } else if (income <= 171550) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (income - 82250) * 0.28;} else if (income <= 372950) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (income - 171550) * 0.33;} else {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (372950 - 171550) * 0.33 + (income - 372950) * 0.35;}} else if (status == 1) { // Compute tax for married file jointly if (income <= 16700) {tax = income * 0.10;} else if (income <= 67900) {tax = 16700 * 0.10 + (income - 16700) * 0.15;} else if (income <= 137050) {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (income - 67900) * 0.25; } else if (income <= 208850) {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (income - 137050) * 0.28;} else if (income <= 372950) {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (208850 - 137050) * 0.28 + (income - 208850) * 0.33;} else {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (171950 - 137050) * 0.28 + (372950 - 208850) * 0.33+ (income - 372950) * 0.35;}} else if (status == 2) { // Compute tax for married separately if (income <= 8350) {tax = income * 0.10;} else if (income <= 33950) {tax = 8350 * 0.10 + (income - 8350) * 0.15;} else if (income <= 68525) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950) * 0.25; } else if (income <= 104425) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (income - 68525) * 0.28;} else if (income <= 186475) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (104425 - 68525) * 0.28 + (income - 104425) * 0.33;} else {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (104425 - 68525) * 0.28 + (186475 - 104425) * 0.33 + (income - 186475) * 0.35;}} else if (status == 3) { // Compute tax for head of household if (income <= 11950) {tax = income * 0.10;} else if (income <= 45500) {tax = 11950 * 0.10 + (income - 11950) * 0.15;} else if (income <= 117450) {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (income - 45500) * 0.25; } else if (income <= 190200) {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (income - 117450) * 0.28;} else if (income <= 372950) {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (190200 - 117450) * 0.28 + (income - 190200) * 0.33;} else {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (190200 - 117450) * 0.28 + (372950 - 190200) * 0.33+ (income - 372950) * 0.35;}} else {System.out.println("Error: Wrong filing status");System.exit(1);}// Display the resultSystem.out.println("Tax is " + (int) (tax * 100) / 100.0);}}3.14public class Exercise03_14 {public static void main(String[] args) {// Obtain the random number 0 or 1int number = (int)(Math.random() * 2);// Prompt the user to enter a guessjava.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Guess head or tail? " +"Enter 0 for head and 1 for tail: ");int guess = input.nextInt();// Check the guessif (guess == number)System.out.println("Correct guess");else if (number == 0)System.out.println("Sorry, it is a head");elseSystem.out.println("Sorry, it is a tail");}}3.15public class Exercise03_15 {public static void main(String[] args) {// Generate a lotteryint lottery = (int)(Math.random() * 1000);// Prompt the user to enter a guessjava.util.Scanner input = new java.util.Scanner(System.in); System.out.print("Enter your lottery pick (three digits): ");int guess = input.nextInt();// Get digitsint l1 = lottery / 100;int l2 = (lottery % 100) / 10; // l2 = (lottery / 10) % 10int l3 = lottery % 10;int g1 = guess / 100;int g2 = (guess % 100) / 10;int g3 = guess % 10;System.out.println("Lottery is " + lottery);// Check the guessif (guess == lottery)System.out.println("Exact match: you win $10,000");else if (g1 == l1 && g3 == l2 && g2 == l3 ||g2 == l1 && g1 == l2 && g3 == l3 ||g2 == l1 && g3 == l2 && g1 == l3 ||g3 == l1 && g1 == l2 && g2 == l3 ||g3 == l1 && g2 == l2 && g1 == l3)System.out.println("Match all digits: you win $3,000"); else if (g1 == l1 || g1 == l2 || g1 == l3 ||g2 == l1 || g2 == l2 || g2 == l3 ||g3 == l1 || g3 == l2 || g3 == l3)System.out.println("Match one digit: you win $1,000"); elseSystem.out.println("Sorry, no match");}}3.16public class Exercise03_16 {public static void main(String[] args) {double x = Math.random() * 100 - 50;double y = Math.random() * 200 - 100;System.out.println(x + ", " + y);}}3.17public class Exercise03_17 {public static void main(String[] args) {// Generate scissor, rock, paperint computerNumber = (int)(Math.random() * 3);// Prompt the user to enter scissor, rock, or paper java.util.Scanner input = new java.util.Scanner(System.in); System.out.print("scissor (0), rock (1), paper (2): ");int userNumber = input.nextInt();// Check the guessswitch (computerNumber) {case 0:if (userNumber == 0)System.out.print("The computer is scissor. You are scissor too. It is a draw");else if (userNumber == 1)System.out.print("The computer is scissor. You are rock. You won");else if (userNumber == 2)System.out.print("The computer is scissor. You are paper. You lost");break;case 1:if (userNumber == 0)System.out.print("The computer is rock. You are scissor. You lost");else if (userNumber == 1)System.out.print("The computer is rock. You are rock too. It is a draw");else if (userNumber == 2)System.out.print("The computer is rock. You are paper. You won");break;case 2:if (userNumber == 0)System.out.print("The computer is paper. You are scissor. You won");else if (userNumber == 1)System.out.print("The computer is paper. You are rock. You lost");else if (userNumber == 2)System.out.print("The computer is paper. You are paper too.It is a draw");break;}}}3.18public class Exercise03_18 {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter package weight: ");double w = input.nextDouble();if (w <= 1) {System.out.println("The shipping cost is $3.5");}else if (w <= 3) {System.out.println("The shipping cost is $5.5");}else if (w <= 10) {System.out.println("The shipping cost is $8.5");}else if (w <= 20) {System.out.println("The shipping cost is $10.5");}else {System.out.println("The package cannot be shipped");}}}3.19public class Exercise03_19 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in); // Enter three edgesSystem.out.print("Enter three edges (length in double): ");double edge1 = input.nextDouble();double edge2 = input.nextDouble();double edge3 = input.nextDouble();。
java语言程序设计基础篇第十版课后答案第二章答案
package cn.Testcx;import java.util.Scanner;public class lesson2 {public static void main(String[] args){@SuppressWarnings("resource")Scanner input =new Scanner(System.in);System.out.print("请输入一个摄氏温度:");double Celsius =input.nextDouble();double Fahrenheit =(9.0/5)*Celsius+32;System.out.println("摄氏温度:"+Celsius+"度"+"转换成华氏温度为:"+Fahrenheit+"度");System.out.print("请输入圆柱的半径和高:");double radius =input.nextDouble();int higth = input.nextInt();double areas =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.println(feet+"英尺转换成米:"+meters);System.out.print("输入一个磅数:");double pounds =input.nextDouble();double kilograms =pounds*0.454;System.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 =totalCurrentTimeMillis/1000;long currentSeconds =totalSeconds%60;long totalMinutes =totalSeconds/60;long currentMinutes =(totalSeconds%(60*60))/60;long currenthours =(totalMinutes/60)%24;System.out.print("输入时区偏移量:");byte zoneOffset = input.nextByte();long currentHour =(currenthours+(zoneOffset*1))%24;System.out.println("当期时区的时间为:"+currentHour+"时"+currentMinutes+"分"+currentSeconds+"秒");System.out.print("请输入v0,v1,t:");double v0 =input.nextDouble();double v1 =input.nextDouble();double t =input.nextDouble();float a = (float) ((v1-v0)/t);System.out.println("平均加速度a="+a);System.out.println("输入水的重量、初始温度、最终温度:");double water =input.nextDouble();double initialTemperature =input.nextDouble();double finalTemperature = input.nextDouble();double Q =water*(finalTemperature-initialTemperature)*4184;System.out.println("所需热量为:"+Q);System.out.print("输入年数:");int numbers =input.nextInt();long oneYearsSecond =365*24*60*60;Long population= (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 lengthOfAirplane =(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.pow(side, 2)))/2;System.out.println("六边形的面积为:"+area);}}。
java语言程序设计基础篇第十版第十三章练习答案
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);}}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 GeometricObjectclass 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、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
第一章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);}}。