《Java语言程序设计(基础篇)》(第10版 梁勇 著)第二十二章练习题答案

合集下载

java语言程序设计基础篇第十版课后答案

java语言程序设计基础篇第十版课后答案

第一章1.1public class Test{public static void main(String[]args){System.out.println("Welcome to Java!"); System.out.println("Welcome to Computer Science!");System.out.println("Progr amming is fun.");}}1.2public class Test{public static void main(String[]args){for(int i=0;i<=4;i++){System.out.println("Welcome to Java!");}}}1.3public class Test{public static void main(String[]args){System.out.println("]");System.out.printl n("]");System.out.println("]]");System.out.println("]]");}}public class Test{public static void main(String[]args){System.out.println("A"); System.out.println("A A");System.out.println("AAAAA");System.out.println("A A");}}public class Test{public static void main(String[]args){System.out.println("V V");System.out.println("V V");System.out.println("V V");System.out.println(" V");}}1.4public class Test{public static void main(String[]args){System.out.println("a a^2a^3");System.out.println("111");System.out.println("248");System.out.println("3 927");System.out.println("41664");}}1.5public class Test{public static void main(String[]args){System.out.println((9.5*4.5-2.5*3)/(45.5-3.5) );}}1.6public class Test{public static void main(String[]args){int i=1,sum=0;for(;i<=9;i++)sum+ =i;System.out.println(sum);}1.7public class Test{public static void main(String[]args){System.out.println(4*(1.0-1.0/3+1.0/5-1.0/7+1.0/9-1.0/11));System.out.println(4*(1.0-1.0/3+1.0/5-1.0/7+1.0/9-1.0/11+1.0/13));}}1.8public class Test{public static void main(String[]args){final double PI=3.14; double radius=5.5;System.out.println(2*radius*PI);System.out.println(PI*radius*radius);}}1.9public class Test{public static void main(String[]args){System.out.println(7.9*4.5);System.out.p rintln(2*(7.9+4.5));}}1.10public class Test{public static void main(String[]args){double S=14/1.6;double T=45*60+30;double speed=S/T;System.out.println(speed);}1.11public class Test{public static void main(String[]args){int BN=312032486; //original person numbers double EveryYS,EveryYBP,EveryYDP,EveryYMP;EveryY S=365*24*60*60;EveryYBP=EveryYS/7;EveryYDP=EveryYS/13;Every YMP=EveryYS/45;int FirstYP,SecondYP,ThirdYP,FourthYP,FivthYP;FirstYP=(int)(BN+EveryYBP+EveryYMP-EveryYDP);SecondYP=(int)(FirstYP +EveryYBP+EveryYMP-EveryYDP);ThirdYP=(int)(SecondYP+EveryYBP+Ev eryYMP-EveryYDP);FourthYP=(int)(ThirdYP+EveryYBP+EveryYMP-EveryYD P);FivthYP=(int)(FourthYP+EveryYBP+EveryYMP-EveryYDP);System.out.pri ntln(FirstYP);System.out.println(SecondYP);System.out.println(ThirdYP);Syste m.out.println(FourthYP);System.out.println(FivthYP);}}1.12public class Test{public static void main(String[]args){double S=24*1.6; double T=(1*60+40)*60+35;double speed=S/T;System.out.println(sp eed);}}1.13import java.util.Scanner;public class Test{public static void main(String[]args){Scanner input=new Scan ner(System.in);System.out.println("input a,b,c,d,e,f value please:");double a=input.nextDouble();double b=input.nextDouble();double c=input.nextDouble();double d=input. nextDouble();double e=input.nextDouble();第二章package cn.Testcx;import java.util.Scanner;public class lesson2{public static void main(String[]args){@SuppressWarnings("resource")Scanner in put=new Scanner(System.in);System.out.print("请输入一个摄氏温度:");double Celsius=input.nextDouble();double Fahrenheit=(9.0/5)*Celsius+3 2;System.out.println("摄氏温度:"+Celsius+"度"+"转换成华氏温度为:"+Fahrenheit+"度");System.out.print("请输入圆柱的半径和高:");double radius=input.nextDouble();int higth=input.nextInt();double are as=radius*radius*Math.PI;double volume=areas*higth;System.out.println("圆柱体的面积为:"+areas);System.out.println("圆柱体的体积为:"+volume);System.out.print("输入英尺数:");double feet=input.nextDouble();double meters=feet*0.305;System.out.print ln(feet+"英尺转换成米:"+meters);System.out.print("输入一个磅数:");double pounds=input.nextDouble();double kilograms=pounds*0.454;Syste m.out.println(pounds+"磅转换成千克为:"+kilograms);System.out.println("输入分钟数:");long minutes=input.nextInt();long years=minutes/(24*60*365);long days=(minutes%(24*60*365))/(24*60);System.out.println(minutes+"分钟"+"有"+years+"年和"+days+"天");long totalCurrentTimeMillis=System.currentTimeMillis();long totalSeconds=t otalCurrentTimeMillis/1000;long currentSeconds=totalSeconds%60;long totalM inutes=totalSeconds/60;long currentMinutes=(totalSeconds%(60*60))/60;long currenthours=(totalMinutes/60)%24;System.out.print("输入时区偏移量:");byte zoneOffset=input.nextByte();long currentHour=(currenthours+(zoneOf fset*1))%24;System.out.println("当期时区的时间为:"+currentHour+"时"+currentMinutes+"分"+currentSeconds+"秒");System.out.print("请输入v0,v1,t:");double v0=input.nextDouble();double v1=input.nextDouble();doublet=input.nextDouble();float a=(float)((v1-v0)/t);System.out.println("平均加速度a="+a);System.out.println("输入水的重量、初始温度、最终温度:");double water=input.nextDouble();double initialTemperature=input.nextDou ble();double finalTemperature=input.nextDouble();double Q=water*(finalTemp erature-initialTemperature)*4184;System.out.println("所需热量为:"+Q);System.out.print("输入年数:");int numbers=input.nextInt();long oneYearsSecond=365*24*60*60;Longpop ulation=(long)((312032486+((oneYearsSecond/7.0)+(oneYearsSecond/45.0)-(oneYearsSecond/13.0))*numbers));System.out.println("第"+numbers+"年后人口总数为:"+population);System.out.print("输入速度单位m/s和加速度a单位m/s2:");double v=input.nextDouble();double a1=input.nextDouble();double l engthOfAirplane=(Math.pow(v,2))/(2*a1);System.out.println("最短长度为:"+lengthOfAirplane);System.out.print("输入存入的钱:");double money=input.nextInt();double monthRate=5.0/1200;for(int i=1;i<7; i++){double total=money*(Math.pow(1+monthRate,i));System.out.println("第"+i+"个月的钱为:"+total);//告诉我书上的银行在哪里,我要去存钱,半年本金直接翻6倍、、、}System.out.print("用户请输入身高(英寸)、体重(磅):");double height=input.nextDouble();double weight=input.nextDouble(); double BMI=(weight*0.45359237)/(Math.pow((height*0.0254),2));System.out.println("BMI的值为"+BMI);System.out.print("输入x1和y1:");System.out.print("输入x2和y2:");double x1=input.nextDouble();double y1=input.nextDouble();double x2 =input.nextDouble();double y2=input.nextDouble();double point1=Math.pow((x2-x1),2);double point2=Math.pow((y2-y1),2);double distance=Math.pow((point1+point2),(1.0/2));//也可以Math.pow((point1+point2),0.5)System.out.println("两点间的距离为:"+distance);System.out.print("输入六边形的边长:");double side=input.nextDouble();double area=(3*(Math.pow(3,0.5))*(Math.p ow(side,2)))/2;System.out.println("六边形的面积为:"+area);}}。

《Java语言程序设计(基础篇)》(第10版 梁勇 著)第九章练习题答案

《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版 梁勇 著)第三十二章练习题答案

《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 += "&nbsp";}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版) 梁勇 课后习题答案

Java语言程序设计基础篇(第10版) 梁勇 课后习题答案

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 !");
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.11 public class Test{ public static void main(String[] args){ int BN = 312032486; //original person numbers double 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();

java语言程序设计基础篇复习题答案

java语言程序设计基础篇复习题答案

java语言程序设计基础篇复习题答案Java语言程序设计基础篇复习题答案一、选择题1. Java是一种( A )。

A. 面向对象的编程语言B. 过程式编程语言C. 汇编语言D. 标记语言2. Java程序的执行流程是( B )。

A. 编译 -> 链接 -> 执行B. 编译 -> 运行C. 链接 -> 编译 -> 执行D. 执行 -> 编译 -> 链接3. 下列哪个是Java的关键字( D )。

A. ObjectB. StringC. IntegerD. class4. Java语言中,哪个是合法的类名( A )。

A. MyClassB. 2classC. my-classD. class5. 在Java中,哪个是正确的主方法声明( C )。

A. public void main(String args[])B. public void main(String[] args)C. public static void main(String[] args)D. static public void main(String args[])6. 下列哪个是Java的基本数据类型( C )。

A. StringB. IntegerC. intD. Object7. Java中,哪个操作符用于连接字符串( B )。

A. +B. +C. +=D. append()8. 以下哪个是Java的控制流语句( D )。

A. forB. whileC. ifD. 所有选项都是9. Java中,哪个是正确的数组声明( A )。

A. int[] numbers;B. int numbers[];C. numbers[] int;D. int numbers[]10. 在Java中,哪个是正确的方法定义( B )。

A. int add(int a, int b) { return a + b; }B. public int add(int a, int b) { return a + b; }C. private int add(int a, int b) { return a + b; }D. static int add(int a, int b) { return a + b; }二、简答题1. 简述Java语言的特点。

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

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语言程序设计基础篇复习题答案

java语言程序设计基础篇复习题答案

java语言程序设计基础篇复习题答案# Java语言程序设计基础篇复习题答案一、选择题1. Java是一种面向对象的编程语言,它是由SUN公司开发的。

(对)2. Java程序的源文件扩展名是.java,编译后的文件扩展名是.class。

(对)3. Java语言是编译型语言,不是解释型语言。

(错)4. Java语言的跨平台特性主要得益于Java虚拟机(JVM)。

(对)5. 在Java中,可以通过`==`操作符来比较两个字符串的内容是否相等。

(错)二、填空题1. Java语言的基本数据类型包括:byte、short、int、long、float、double、char、boolean。

2. Java中用`public class`定义类时,类名必须与文件名相同。

3. Java程序的入口方法是`main`方法,它必须声明为`public static void main(String[] args)`。

4. Java中,`new`关键字用于创建对象。

5. 访问控制修饰符包括:public、private、protected、default(无修饰符)。

三、简答题1. 简述Java语言的特点。

- Java是一种面向对象的编程语言,具有封装、继承和多态性。

- Java是平台无关的,可以在任何安装了Java虚拟机的设备上运行。

- Java具有强类型检查,提高了代码的安全性和可读性。

- Java提供了丰富的标准库,方便开发者快速开发。

2. 解释Java中的异常处理机制。

- Java使用try-catch-finally块来处理异常。

- try块包含可能会抛出异常的代码。

- catch块用于捕获并处理异常。

- finally块中的代码无论是否发生异常都会执行,常用于资源的清理。

3. 描述Java中集合框架的基本概念。

- Java集合框架是一组相关的接口和类,用于存储和处理对象集合。

- 基本接口包括:Collection、List、Set、Map。

(完整版)Java语言程序设计(基础篇)原书第十版梁勇著第一章答案

(完整版)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语言程序设计(基础篇)答案

3.4import javax.swing.*;public class AdditionTutor{public static void main(String[] args){int number1=(int)(System.currentTimeMillis()%100);int number2=(int)(System.currentTimeMillis()*5%100);String answerString=JOptionPane.showInputDialog("what is "+ number1 +"+ "+ number2+" ?");int answer=Integer.parseInt(answerString);JOptionPane.showMessageDialog(null,number1 +" + "+ number2 +" = "+answer+" is "+(number1+number2==answer));}}3.10import javax.swing.JOptionPane;public class ComputeTaxWithSelectionStatement{public static void main(String[] args){//Prompt the user to enter filing statusString statusString = JOptionPane.showInputDialog("Enter the filing status:\n"+"(0-single filer,1-married jointly,\n"+"2-married separately,3-head of household)");int status = Integer.parseInt(statusString);//Prompt the user to enter taxable incomeString incomeString = JOptionPane.showInputDialog("Enter the taxable income:");double income = Double.parseDouble(incomeString);//Comput taxdouble tax=0;if (status == 0){//Compute tax for single filersif (income <= 6000)tax = income * 0.10;else if (income <= 27950)tax = 6000 * 0.10 + (income - 6000) * 0.15;else if (income <= 67700)tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +(income - 27950) * 0.27;else if (income <= 141250)tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +(67700 - 27950) * 0.27 + (income - 67700) * 0.30;else if (income <=307050)tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +(67700 - 27950) * 0.27 + (141250 - 67700) * 0.30 +(income - 141250) * 0.35;elsetax = 6000 * 0.10 + (27950 - 6000) * 0.15 +(67700 - 27950) * 0.27 + (141250 -67700) * 0.30 +(307050 - 141250) * 0.35 + (income - 307050) * 0.386;}else if (status == 1){//Compute tax for married file jointly if (income <= 12000)tax = income * 0.10;else if (income <= 46700)tax = 12000 * 0.10 + (income - 12000) * 0.15;else if (income <= 112850)tax = 12000 * 0.10 + (46700 - 12000) * 0.15 +(income - 46700) * 0.27;else if (income <= 171950)tax = 12000 * 0.10 + (46700 - 12000) * 0.15 +(112850 - 46700) * 0.27 + (income - 112850) * 0.30;else if (income <= 307050)tax = 12000 * 0.10 + (46700 - 12000) * 0.15 +(112850 - 46700) * 0.27 + (141250 - 112850) * 0.30 +(income - 307050) * 0.35;elsetax = 12000 * 0.10 + (46700 - 12000) * 0.15 +(112850 - 46700 ) * 0.27 + (171950 - 112850) * 0.30 +(307050 - 171950) * 0.35 + (income - 307050) * 0.386;}else if (status == 2){//Compute tax for married separately if (income <= 6000)tax = income * 0.10;else if (income <= 23350)tax = 6000 * 0.10 + (income - 6000) * 0.15;else if (income <= 56425)tax = 6000 * 0.10 + (23350 - 6000) * 0.15 +(income - 23350) * 0.27;else if (income <= 85975)tax = 6000 * 0.10 + (23350 - 6000) * 0.15 +(56425 - 23350) * 0.27 + (income - 56425) * 0.30;else if (income <= 153525)tax = 6000 * 0.10 + (23350 - 6000) * 0.15 +(56425 - 23350) * 0.27 + (85975 - 56425) * 0.30 +(income - 85975) * 0.35;elsetax = 6000 * 0.10 + (23350 - 6000) * 0.15 +(56425 - 23350) * 0.27 + (85975 - 56425) * 0.30 +(153525 - 85975) * 0.35 + (income - 153525) * 0.386;}else if (status == 3){//Compute tax for head of householdif (income <= 10000)tax = income * 0.10;else if (income <= 37450)tax = 10000 * 0.10 + (income - 10000) * 0.15;else if (income <= 96700)tax = 10000 * 0.10 + (37450 - 10000) * 0.15 +(income - 37450) * 0.27;else if (income <= 156600)tax = 10000 * 0.10 + (37450 - 10000) * 0.15 +(96700 - 37450) * 0.27 + (income - 96700) * 0.30;else if (income <= 307050)tax = 10000 * 0.10 + (37450 - 10000) * 0.15 +(96700 - 37450) * 0.27 + (156600 - 96700) * 0.30 +(income - 156600) * 0.35;elsetax = 10000 * 0.10 + (37450 - 10000) * 0.15 +(96700 - 37450) * 0.27 + (156600 - 96700) * 0.30 +(307050 - 156600) * 0.35 + (income - 307050) * 0.386;}else{System.out.println("Error: invalid status");System.exit(0);}//Display the resultJOptionPane.showMessageDialog(null,"Tax is " +(int)(tax * 100) / 100.0);}}4.11public class ZhengChu{public static void main(String[] args){int count=0;for(int i=100;i<=200;i++){if((i%5==0||i%6==0)&&i%30!=0){System.out.print(" "+ i);count++;if(count%10==0)System.out.println();}}}}4.14public class ASCII{public static void main(String[] args){int count = 0;for(int i = 33; i <= 126; i++){count++;char ch = (char)i;System.out.print(" " + ch);if(count % 10 == 0)System.out.println();}}}4.17import javax.swing.JOptionPane;public class FindSalesAmount{/**Main method*/public static void main(String[] args){//The commission soughtString COMMISSION_SOUGHTString = JOptionPane.showInputDialog("Enter the COMMISSION_SOUGHT :");double COMMISSION_SOUGHT = Double.parseDouble(COMMISSION_SOUGHTString);double commission = 0;double salesAmount;for (salesAmount = 0.01;commission <= COMMISSION_SOUGHT;){salesAmount += 0.01; //防止犯off-by-one错误,先判断在做自加!if (salesAmount >= 10000.01)commission =5000 * 0.08 + 5000 * 0.1 + (salesAmount - 10000) * 0.12;else if (salesAmount >= 5000.01)commission = 5000 * 0.08 + (salesAmount - 5000) * 0.10;elsecommission = salesAmount * 0.08;}String output ="The sales amount $" + (int)(salesAmount * 100) / 100.0 +"\n is needed to make a commission of $" + COMMISSION_SOUGHT;JOptionPane.showMessageDialog(null,output);}}5.6import javax.swing.JOptionPane;public class PrintPyramid{public static void main(String[] args){String input = JOptionPane.showInputDialog("Enter the number of lines:");int numberOfLines = Integer.parseInt(input);displayPattern(numberOfLines);}public static void displayPattern(int n){for (int row = 1;row <= n;row++){for (int column = 1;column <= n - row;column++)System.out.print(" ");for (int num = row;num >= 1;num--)System.out.print((num >= 10) ? " " + num : " " + num);System.out.println();}}}5.18public class MathSuanFa{public static void main(String[] args){double A = Math.sqrt(4);double B = (int)Math.sin(2 * Math.PI);double C = (int)Math.cos(2 * Math.PI);double D = (int)Math.pow(2, 2);double E = (int)Math.log(Math.E);double F = (int)(Math.exp(1)*100000)/100000.0;double G = (int)Math.max(2, Math.min(3, 4));double H = (int)Math.rint(-2.5);double I = (int)Math.ceil(-2.5);double J = (int)Math.floor(-2.5);int K = (int)Math.round(-2.5f);int L = (int)Math.round(-2.5);double M = (int)Math.rint(2.5);double N = (int)Math.ceil(2.5);double O = (int)Math.floor(2.5);int P = (int)Math.round(2.5f);int Q = (int)Math.round(2.5);int R = (int)Math.round(Math.abs(-2.5));System.out.println(A +" "+ B +" "+ C +" "+ D +" "+ E +" "+ F +" "+ G +" "+ H +" "+ I +" "+ J +" "+ K +" "+ L +" "+ M +" "+ N +" "+ O +" "+ P +" "+ Q +" "+ R);}}6.9import javax.swing.JOptionPane;public class Array{public static void main (String[] args){String incomeString = JOptionPane.showInputDialog("Enter the number of array size:");int income = Integer.parseInt(incomeString);int arraySize = income;int [] myList = new int [arraySize];int m;for ( m = 0; m < arraySize; m++){String elementString = JOptionPane.showInputDialog("Enter the " + (m + 1) + " element of the array");int element = Integer.parseInt(elementString);myList[m] = element;}int minElement = myList[0];for (int i=1; i < arraySize; i++){if (myList[i] < minElement)minElement = myList[i];}JOptionPane.showMessageDialog(null,"The min element is: " + minElement); }}。

Java语言程序设计(基础篇)(第10版 梁勇著)第二章练习题答案

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版 梁勇 著)第二十一章练习题答案

《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(">", "&gt;");text = text.replaceAll("<", "&lt;");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", "&lt;");else if (text.charAt(token.length()) == '>')output.format("%s", "&gt;");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版 梁勇 著)第二十九章练习题答案

《Java语言程序设计(基础篇)》(第10版 梁勇 著)第二十九章练习题答案

《Java语言程序设计(基础篇)》(第10版梁勇著)第二十九章练习题答案29.3/** Solution provided by N鎠je Frode, April 2013 */public class Exercise29_03 {public static void main(String[] args) {int [][] edges = new int[][]{{0, 1, 2}, {0, 3, 8},{1, 0, 2}, {1, 2, 7}, {1, 3, 3},{2, 1, 7}, {2, 3, 4}, {2, 4, 5},{3, 0, 8}, {3, 1, 3}, {3, 2, 4}, {3, 4, 6},{4, 2, 5}, {4, 3, 6}};Integer[][] adjacencyMatrix = {{null, 2,null, 8,null},{ 2,null, 7, 3,null},{null, 7,null, 4, 5},{ 8, 3, 4,null, 6},{null,null, 5, 6,null}};System.out.println("\nSolution with adjacency matrix:");WeightedGraphAdj<Integer> graph = new WeightedGraphAdj<>(edges, 5); WeightedGraphAdj<Integer>.ShortestPathTree tree =graph.getShortestPathAdj(3, adjacencyMatrix);tree.printAllPaths();}}29.4\import java.util.ArrayList;import java.util.List;import java.util.Scanner;public class Exercise29_04 {public static void main(String[] args) {new Exercise29_04();}public Exercise29_04() {// Prompt the user to enter nine coins H抯 and T'sSystem.out.print("Enter an initial nine coin H抯 and T's: ");Scanner input = new Scanner(System.in);String s = input.nextLine();char[] initialNode = s.toCharArray();ModifiedWeightedNineTailModel model = new ModifiedWeightedNineTailModel();java.util.List<Integer> path =model.getShortestPath(NineTailModel.getIndex(initialNode));System.out.println("The steps to flip the coins are ");for (int i = 0; i < path.size(); i++)NineTailModel.printNode(NineTailModel.getNode(path.get(i).intValue()));System.out.println("The number of flips is " +model.getNumberOfFlips(NineTailModel.getIndex(initialNode)));}public static class ModifiedWeightedNineTailModel extends NineTailModel { /** Construct a model */public ModifiedWeightedNineTailModel() {// Create edgesList<WeightedEdge> edges = getEdges();// Create a graphWeightedGraph<Integer> graph = new WeightedGraph<Integer>(edges, NUMBER_OF_NODES);// Obtain a BSF tree rooted at the target nodetree = graph.getShortestPath(511);}/** Create all edges for the graph */private List<WeightedEdge> getEdges() {// Store edgesList<WeightedEdge> edges = new ArrayList<WeightedEdge>();for (int u = 0; u < NUMBER_OF_NODES; u++) {for (int k = 0; k < 9; k++) {char[] node = getNode(u); // Get the node for vertex uif (node[k] == 'H') {int v = getFlippedNode(node, k);int numberOfFlips = getNumberOfFlips(u, v);// Add edge (v, u) for a legal move from node u to node v edges.add(new WeightedEdge(v, u, numberOfFlips));}}}return edges;}private static int getNumberOfFlips(int u, int v) {char[] node1 = getNode(u);char[] node2 = getNode(v);int count = 0; // Count the number of different cellsfor (int i = 0; i < node1.length; i++)if (node1[i] != node2[i]) count++;return 3 * count;}public int getNumberOfFlips(int u) {return (int)((WeightedGraph<Integer>.ShortestPathTree)tree).getCost(u);}}}29.5import java.util.ArrayList;import java.util.List;public class Exercise29_05 {public static void main(String[] args) {NineTailModel model1 = new NineTailModel();WeightedNineTailModel model2 = new WeightedNineTailModel();AbstractGraph.Tree tree1 = model1.tree;AbstractGraph.Tree tree2 = model2.tree;for (int i = 0; i < 511; i++) {// System.out.println(tree1.depth(i));if (depth(tree1, i) != depth(tree2, i))System.out.println(i);}System.out.println("Finished");}private static int depth(AbstractGraph.Tree tree, int v) {return tree.getPath(v).size();}public static class ModifiedWeightedNineTailModel extends NineTailModel { /** Construct a model */public ModifiedWeightedNineTailModel() {// Create edgesList<WeightedEdge> edges = getEdges();// Create a graphWeightedGraph<Integer> graph = new WeightedGraph<Integer>(edges, NUMBER_OF_NODES);// Obtain a BSF tree rooted at the target nodetree = graph.getShortestPath(511);}/** Create all edges for the graph */private List<WeightedEdge> getEdges() {// Store edgesList<WeightedEdge> edges = new ArrayList<WeightedEdge>();for (int u = 0; u < NUMBER_OF_NODES; u++) {for (int k = 0; k < 9; k++) {char[] node = getNode(u); // Get the node for vertex uif (node[k] == 'H') {int v = getFlippedNode(node, k);int numberOfFlips = getNumberOfFlips(u, v);// Add edge (v, u) for a legal move from node u to node vedges.add(new WeightedEdge(v, u, numberOfFlips));}}}return edges;}private static int getNumberOfFlips(int u, int v) {char[] node1 = getNode(u);char[] node2 = getNode(v);int count = 0; // Count the number of different cellsfor (int i = 0; i < node1.length; i++)if (node1[i] != node2[i]) count++;return 3 * count;}public int getNumberOfFlips(int u) {return (int)((WeightedGraph<Integer>.ShortestPathTree)tree).getCost(u);}}}29.9public class Exercise29_09 {public static void main(String[] args) throws Exception {java.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Enter a file name: ");java.io.File file = new java.io.File(input.nextLine());if (!file.exists()) {System.out.println("File does not exist");System.exit(1);}java.util.Scanner inFile = new java.util.Scanner(file);// Read the number of verticesString s = inFile.nextLine();int numberOfVertices = Integer.parseInt(s);System.out.println("The number of vertices is " + numberOfVertices); java.util.List<WeightedEdge> list =new java.util.ArrayList<WeightedEdge>();while (inFile.hasNext()) {s = inFile.nextLine();String[] triplets = s.split("[\\|]");for (String triplet: triplets) {String[] tokens = triplet.split("[,]");int u = Integer.parseInt(tokens[0].trim());int v = Integer.parseInt(tokens[1].trim());int w = Integer.parseInt(tokens[2].trim());list.add(new WeightedEdge(u, v, w));list.add(new WeightedEdge(v, u, w));}}WeightedGraph<Integer> graph = new WeightedGraph<Integer>(list, numberOfVertices);graph.printWeightedEdges();WeightedGraph<Integer>.MST tree = graph.getMinimumSpanningTree();System.out.println("Total weight in MST is " + tree.getTotalWeight()); tree.printTree();}}29.10public class Exercise29_10 {public static void main(String[] args) throws java.io.FileNotFoundException {String[] vertices = {"Seattle", "San Francisco", "Los Angeles", "Denver", "Kansas City", "Chicago", "Boston", "New York","Atlanta", "Miami", "Dallas", "Houston"};int[][] edges = {{0, 1, 807}, {0, 3, 1331}, {0, 5, 2097},{1, 0, 807}, {1, 2, 381}, {1, 3, 1267},{2, 1, 381}, {2, 3, 1015}, {2, 4, 1663}, {2, 10, 1435},{3, 0, 1331}, {3, 1, 1267}, {3, 2, 1015}, {3, 4, 599},{3, 5, 1003},{4, 2, 1663}, {4, 3, 599}, {4, 5, 533}, {4, 7, 1260},{4, 8, 864}, {4, 10, 496},{5, 0, 2097}, {5, 3, 1003}, {5, 4, 533},{5, 6, 983}, {5, 7, 787},{6, 5, 983}, {6, 7, 214},{7, 4, 1260}, {7, 5, 787}, {7, 6, 214}, {7, 8, 888},{8, 4, 864}, {8, 7, 888}, {8, 9, 661},{8, 10, 781}, {8, 11, 810},{9, 8, 661}, {9, 11, 1187},{10, 2, 1435}, {10, 4, 496}, {10, 8, 781}, {10, 11, 239},{11, 8, 810}, {11, 9, 1187}, {11, 10, 239}};java.io.PrintWriter output = newjava.io.PrintWriter("Exercise28_10.txt");int numberOfVertices = vertices.length;output.println(numberOfVertices);for (int startingVertex = 0; startingVertex < numberOfVertices; startingVertex++) {int count = 0;for (int i = 0; i < edges.length; i++) {if (edges[i][0] == startingVertex && edges[i][0] < edges[i][1]) {count++;if (count == 1)output.print(edges[i][0] + ", "+ edges[i][1] + ", "+ edges[i][2]);elseoutput.print(" | " + edges[i][0] + ", " + edges[i][1] + ", " + edges[i][2]);}}if (count > 0) output.println();}System.out.println("Done!");output.close();}}29.11public class Exercise29_11 {public static void main(String[] args) throws Exception {java.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Enter a file name: ");java.io.File file = new java.io.File(input.nextLine());if (!file.exists()) {System.out.println("File does not exist");System.exit(1);}// Read two verticesSystem.out.print("Enter two vertices (integer indexes): ");int v1 = input.nextInt();int v2 = input.nextInt();java.util.Scanner inFile = new java.util.Scanner(file);// Read the number of verticesString s = inFile.nextLine();int numberOfVertices = Integer.parseInt(s);System.out.println("The number of vertices is " + numberOfVertices); java.util.List<WeightedEdge> list = new java.util.ArrayList<>();while (inFile.hasNext()) {s = inFile.nextLine();String[] triplets = s.split("[\\|]");for (String triplet: triplets) {String[] tokens = triplet.split("[,]");int u = Integer.parseInt(tokens[0].trim());int v = Integer.parseInt(tokens[1].trim());int w = Integer.parseInt(tokens[2].trim());list.add(new WeightedEdge(u, v, w));list.add(new WeightedEdge(v, u, w));}}WeightedGraph<Integer> graph = new WeightedGraph<>(list, numberOfVertices);graph.printWeightedEdges();WeightedGraph<Integer>.ShortestPathTree tree =graph.getShortestPath(v1);tree.printPath(v2);}29.12import java.util.List;import javafx.application.Application;import javafx.scene.Scene;import yout.Pane;import javafx.scene.shape.Circle;import javafx.scene.shape.Line;import javafx.scene.text.Text;import javafx.stage.Stage;public class Exercise29_12 extends Application {private City[] vertices = { new City("Seattle", 75, 50),new City("San Francisco", 50, 210),new City("Los Angeles", 75, 275), new City("Denver", 275, 175),new City("Kansas City", 400, 245),new City("Chicago", 450, 100), new City("Boston", 700, 80),new City("New York", 675, 120), new City("Atlanta", 575, 295),new City("Miami", 600, 400), new City("Dallas", 408, 325),new City("Houston", 450, 360) };private int[][] edges = {{0, 1, 807}, {0, 3, 1331}, {0, 5, 2097},{1, 0, 807}, {1, 2, 381}, {1, 3, 1267},{2, 1, 381}, {2, 3, 1015}, {2, 4, 1663}, {2, 10, 1435},{3, 0, 1331}, {3, 1, 1267}, {3, 2, 1015}, {3, 4, 599},{3, 5, 1003},{4, 2, 1663}, {4, 3, 599}, {4, 5, 533}, {4, 7, 1260},{4, 8, 864}, {4, 10, 496},{5, 0, 2097}, {5, 3, 1003}, {5, 4, 533},{5, 6, 983}, {5, 7, 787},{6, 5, 983}, {6, 7, 214},{7, 4, 1260}, {7, 5, 787}, {7, 6, 214}, {7, 8, 888},{8, 4, 864}, {8, 7, 888}, {8, 9, 661},{8, 10, 781}, {8, 11, 810},{9, 8, 661}, {9, 11, 1187},{10, 2, 1435}, {10, 4, 496}, {10, 8, 781}, {10, 11, 239},{11, 8, 810}, {11, 9, 1187}, {11, 10, 239}};private WeightedGraph<City> graph1 = new WeightedGraph<>(vertices, edges); private GraphView view = new GraphView(graph1);@Override // Override the start method in the Application class public void start(Stage primaryStage) {// Create a scene and place it in the stageScene scene = new Scene(view, 450, 350);primaryStage.setTitle("Exercise29_12"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage}class GraphView extends Pane {Graph<? extends Displayable> graph;public GraphView(Graph<? extends Displayable> graph) {this.graph = graph;paint();}protected void paint() {// Draw verticesList<? extends Displayable> vertices = graph.getVertices();for (int i = 0; i < graph.getSize(); i++) {int x = vertices.get(i).getX();int y = vertices.get(i).getY();String name = vertices.get(i).getName();getChildren().addAll(new Circle(x, y, 8),new Text(x - 12, y - 12, name));}// Display edges and weightsfor (int i = 0; i < graph.getSize(); i++) {List<Integer> neighbors = graph.getNeighbors(i);for (int j = 0; j < neighbors.size(); j++) {int v = neighbors.get(j);int x1 = graph.getVertex(i).getX();int y1 = graph.getVertex(i).getY();int x2 = graph.getVertex(v).getX();int y2 = graph.getVertex(v).getY();try {getChildren().addAll(new Line(x1, y1, x2, y2),new Text((x1 + x2) / 2, (y1 + y2) / 2 - 6,((WeightedGraph)graph).getWeight(i, v) + ""));}catch (Exception ex) {ex.printStackTrace();}}}}}class City implements Displayable {private int x, y;private String name;City(String name, int x, int y) { = name;this.x = x;this.y = y;}public int getX() {return x;}public int getY() {return y;}public String getName() {return name;}public boolean equals(Object o) {return ((City)o).name.equals();}}/*** 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);}}29.13import java.util.List;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.Pane;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.shape.Line;import javafx.scene.text.Text;import javafx.stage.Stage;public class Exercise29_13 extends Application {private City[] vertices = { new City("Seattle", 75, 50), new City("San Francisco", 50, 210),new City("Los Angeles", 75, 275), new City("Denver", 275, 175), new City("Kansas City", 400, 245),new City("Chicago", 450, 100), new City("Boston", 700, 80),new City("New York", 675, 120), new City("Atlanta", 575, 295),new City("Miami", 600, 400), new City("Dallas", 408, 325),new City("Houston", 450, 360) };private int[][] edges = {{0, 1, 807}, {0, 3, 1331}, {0, 5, 2097},{1, 0, 807}, {1, 2, 381}, {1, 3, 1267},{2, 1, 381}, {2, 3, 1015}, {2, 4, 1663}, {2, 10, 1435},{3, 0, 1331}, {3, 1, 1267}, {3, 2, 1015}, {3, 4, 599},{3, 5, 1003},{4, 2, 1663}, {4, 3, 599}, {4, 5, 533}, {4, 7, 1260},{4, 8, 864}, {4, 10, 496},{5, 0, 2097}, {5, 3, 1003}, {5, 4, 533},{5, 6, 983}, {5, 7, 787},{6, 5, 983}, {6, 7, 214},{7, 4, 1260}, {7, 5, 787}, {7, 6, 214}, {7, 8, 888},{8, 4, 864}, {8, 7, 888}, {8, 9, 661},{8, 10, 781}, {8, 11, 810},{9, 8, 661}, {9, 11, 1187},{10, 2, 1435}, {10, 4, 496}, {10, 8, 781}, {10, 11, 239},{11, 8, 810}, {11, 9, 1187}, {11, 10, 239}};private WeightedGraph<City> graph1 = new WeightedGraph<>(vertices, edges); private GraphView view = new GraphView(graph1);private Label lblStatus = new Label();private TextField tfStartCity = new TextField();private TextField tfEndCity = new TextField();private Button btSP = new Button("Display Shortest Path");@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {HBox hBox = new HBox();hBox.getChildren().addAll(new Label("Starting City:"),tfStartCity, new Label("Ending City:"), tfEndCity, btSP);hBox.setAlignment(Pos.CENTER);BorderPane pane = new BorderPane();pane.setCenter(view);pane.setBottom(hBox);pane.setTop(lblStatus);BorderPane.setAlignment(lblStatus, Pos.CENTER);// Create a scene and place it in the stageScene scene = new Scene(pane, 450, 350);primaryStage.setTitle("Exercise29_13"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagebtSP.setOnAction( e -> {String name1 = tfStartCity.getText();int index1 = graph1.getIndex(new City(name1, 0, 0));if (index1 < 0) {lblStatus.setText(name1 + " is not in the map");return;}String name2 = tfEndCity.getText();int index2 = graph1.getIndex(new City(name2, 0, 0));if (index2 < 0)lblStatus.setText(name2 + " is not in the map");else {List<City> path = graph1.getShortestPath(index1).getPath(index2); view.setPath(path);}});}class GraphView extends Pane {private Graph<? extends Displayable> graph;private List<? extends Displayable> path;public GraphView(Graph<? extends Displayable> graph) {this.graph = graph;paint();}public void setPath(List<? extends Displayable> path) {this.path = path;paint();}protected void paint() {// Draw verticesList<? extends Displayable> vertices = graph.getVertices();for (int i = 0; i < graph.getSize(); i++) {int x = vertices.get(i).getX();int y = vertices.get(i).getY();String name = vertices.get(i).getName();getChildren().addAll(new Circle(x, y, 8),new Text(x - 12, y - 12, name));}// Display edges and weightsfor (int i = 0; i < graph.getSize(); i++) {List<Integer> neighbors = graph.getNeighbors(i);for (int j = 0; j < neighbors.size(); j++) {int v = neighbors.get(j);int x1 = graph.getVertex(i).getX();int y1 = graph.getVertex(i).getY();int x2 = graph.getVertex(v).getX();int y2 = graph.getVertex(v).getY();try {getChildren().addAll(new Line(x1, y1, x2, y2), new Text((x1 + x2) / 2, (y1 + y2) / 2 - 6, ((WeightedGraph)graph).getWeight(i, v) + ""));}catch (Exception ex) {ex.printStackTrace();}}}// Display the pathif (path == null) return;for (int i = 1; i < path.size(); i++) {int x1 = path.get(i).getX();int y1 = path.get(i).getY();int x2 = path.get(i - 1).getX();int y2 = path.get(i - 1).getY();Line line = new Line(x1, y1, x2, y2);line.setStroke(Color.RED);line.setStrokeWidth(3);this.getChildren().add(line);}}}class City implements Displayable {private int x, y;private String name;City(String name, int x, int y) { = name;this.x = x;this.y = y;}public int getX() {return x;}public int getY() {return y;}public String getName() {return name;}public boolean equals(Object o) {return ((City)o).name.equals();}}/*** 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);}}29.14import java.util.List;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.Pane;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.shape.Line;import javafx.scene.text.Text;import javafx.stage.Stage;public class Exercise29_14 extends Application {private City[] vertices = { new City("Seattle", 75, 50),new City("San Francisco", 50, 210),new City("Los Angeles", 75, 275), new City("Denver", 275, 175), new City("Kansas City", 400, 245),new City("Chicago", 450, 100), new City("Boston", 700, 80),new City("New York", 675, 120), new City("Atlanta", 575, 295), new City("Miami", 600, 400), new City("Dallas", 408, 325),new City("Houston", 450, 360) };private int[][] edges = {{0, 1, 807}, {0, 3, 1331}, {0, 5, 2097},{1, 0, 807}, {1, 2, 381}, {1, 3, 1267},{2, 1, 381}, {2, 3, 1015}, {2, 4, 1663}, {2, 10, 1435},{3, 0, 1331}, {3, 1, 1267}, {3, 2, 1015}, {3, 4, 599},{3, 5, 1003},{4, 2, 1663}, {4, 3, 599}, {4, 5, 533}, {4, 7, 1260},{4, 8, 864}, {4, 10, 496},{5, 0, 2097}, {5, 3, 1003}, {5, 4, 533},{5, 6, 983}, {5, 7, 787},{6, 5, 983}, {6, 7, 214},{7, 4, 1260}, {7, 5, 787}, {7, 6, 214}, {7, 8, 888},{8, 4, 864}, {8, 7, 888}, {8, 9, 661},{8, 10, 781}, {8, 11, 810},{9, 8, 661}, {9, 11, 1187},{10, 2, 1435}, {10, 4, 496}, {10, 8, 781}, {10, 11, 239},{11, 8, 810}, {11, 9, 1187}, {11, 10, 239}};private WeightedGraph<City> graph1 = new WeightedGraph<>(vertices, edges); private GraphView view = new GraphView(graph1,graph1.getMinimumSpanningTree());private Label lblStatus = new Label();private TextField tfStartCity = new TextField();private TextField tfEndCity = new TextField();private Button btSP = new Button("Display Shortest Path");@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {BorderPane pane = new BorderPane();pane.setCenter(view);BorderPane.setAlignment(lblStatus, Pos.CENTER);// Create a scene and place it in the stageScene scene = new Scene(pane, 450, 350);primaryStage.setTitle("Exercise29_14"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stage}class GraphView extends Pane {private Graph<? extends Displayable> graph;private AbstractGraph<? extends Displayable>.Tree tree;public GraphView(Graph<? extends Displayable> graph,AbstractGraph<? extends Displayable>.Tree tree) {this.graph = graph;this.tree = tree;paint();}public void setTree(AbstractGraph<? extends Displayable>.Tree tree) { this.tree = tree;paint();}protected void paint() {// Draw verticesList<? extends Displayable> vertices = graph.getVertices();for (int i = 0; i < graph.getSize(); i++) {int x = vertices.get(i).getX();int y = vertices.get(i).getY();String name = vertices.get(i).getName();getChildren().addAll(new Circle(x, y, 8),new Text(x - 12, y - 12, name));}// Display edges and weightsfor (int i = 0; i < graph.getSize(); i++) {List<Integer> neighbors = graph.getNeighbors(i);for (int j = 0; j < neighbors.size(); j++) {int v = neighbors.get(j);int x1 = graph.getVertex(i).getX();int y1 = graph.getVertex(i).getY();int x2 = graph.getVertex(v).getX();int y2 = graph.getVertex(v).getY();try {getChildren().addAll(new Line(x1, y1, x2, y2),new Text((x1 + x2) / 2, (y1 + y2) / 2 - 6,((WeightedGraph)graph).getWeight(i, v) + ""));}catch (Exception ex) {ex.printStackTrace();}}}// Highlight the edges in the spanning treeif (tree == null) return;for (int i = 0; i < graph.getSize(); i++) {if (tree.getParent(i) != -1) {int v = tree.getParent(i);int x1 = graph.getVertex(i).getX();int y1 = graph.getVertex(i).getY();int x2 = graph.getVertex(v).getX();int y2 = graph.getVertex(v).getY();drawArrowLine(x1, y1, x2, y2, this);}}}}public static void drawArrowLine(double x1, double y1, double x2, double y2, Pane pane) {Line line1 = new Line(x1, y1, x2, y2);line1.setStroke(Color.RED);pane.getChildren().add(line1);// find slope of this linedouble slope = ((((double) y1) - (double) y2))/ (((double) x1) - (((double) x2)));double arctan = Math.atan(slope);// This will flip the arrow 45 off of a// perpendicular line at pt x2double set45 = 1.57 / 2;// arrows should always point towards i, not i+1if (x1 < x2) {// add 90 degrees to arrow linesset45 = -1.57 * 1.5;}// set length of arrowsint arrlen = 15;// draw arrows on lineLine line2 = new Line(x2, y2, (x2 + (Math.cos(arctan + set45) * arrlen)), ((y2)) + (Math.sin(arctan + set45) * arrlen));line2.setStroke(Color.RED);pane.getChildren().add(line2);Line line3 = new Line(x2, y2, (x2 + (Math.cos(arctan - set45) * arrlen)), ((y2)) + (Math.sin(arctan - set45) * arrlen));line3.setStroke(Color.RED);pane.getChildren().add(line3);}class City implements Displayable {private int x, y;private String name;City(String name, int x, int y) { = name;this.x = x;this.y = y;}public int getX() {return x;}public int getY() {return y;}public String getName() {return name;}public boolean equals(Object o) {return ((City)o).name.equals();}}/*** 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);}}29.15import java.util.List;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.GridPane;import yout.HBox;import yout.Pane;import yout.VBox;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.shape.Line;import javafx.scene.text.Text;import javafx.stage.Stage;public class Exercise29_15 extends Application {private TextField tfVertexName = new TextField();private TextField tfX = new TextField();private TextField tfY = new TextField();private Button btAddVertex = new Button("Add Vertex");private TextField tfu = new TextField();private TextField tfv = new TextField();private TextField tfWeight = new TextField();private Button btAddEdge = new Button("Add Edge");private TextField tfStartVertex = new TextField();private TextField tfEndVertex = new TextField();private Button btFindShortestPath = new Button("Shortest Path");private Button btStartOver = new Button("Start Over (Clear Graphs)"); private Label lblStatus = new Label();private WeightedGraph<Vertex> graph = new WeightedGraph<>(); private GraphView view = new GraphView(graph);@Override // Override the start method in the Application class public void start(Stage primaryStage) {GridPane gridPane1 = new GridPane();gridPane1.add(new Label("Add a new vertex"), 0, 0);gridPane1.add(new Label("Vertex name:"), 0, 1);gridPane1.add(new Label("x-coordinate:"), 0, 2);gridPane1.add(new Label("y-coordinate:"), 0, 3);gridPane1.add(tfVertexName, 1, 1);gridPane1.add(tfX, 1, 2);gridPane1.add(tfY, 1, 3);gridPane1.add(btAddVertex, 1, 4);GridPane gridPane2 = new GridPane();gridPane2.add(new Label("Add a new edge"), 0, 0);gridPane2.add(new Label("Vertex u (index):"), 0, 1);gridPane2.add(new Label("Vertex v (index):"), 0, 2);gridPane2.add(new Label("Weight:"), 0, 3);gridPane2.add(tfu, 1, 1);gridPane2.add(tfv, 1, 2);gridPane2.add(tfWeight, 1, 3);gridPane2.add(btAddEdge, 1, 4);GridPane gridPane3 = new GridPane();gridPane3.add(new Label("Find a shortest path"), 0, 0);gridPane3.add(new Label("Starting vertex:"), 0, 1);gridPane3.add(new Label("Ending vertex:"), 0, 2);gridPane3.add(tfStartVertex, 1, 1);gridPane3.add(tfEndVertex, 1, 2);gridPane3.add(btFindShortestPath, 1, 3);HBox hBox = new HBox(5);hBox.setAlignment(Pos.CENTER);hBox.getChildren().addAll(gridPane1, gridPane2, gridPane3);VBox vBox = new VBox(5);vBox.setAlignment(Pos.CENTER);vBox.getChildren().addAll(hBox, btStartOver);BorderPane pane = new BorderPane();pane.setCenter(view);pane.setBottom(vBox);BorderPane.setAlignment(lblStatus, Pos.CENTER);。

Java语言程序设计基础篇课后答案-机械工业出版社[资料]

Java语言程序设计基础篇课后答案-机械工业出版社[资料]

Java语言程序设计基础篇课后答案-机械工业出版社Java语言程序设计1 / 81&[编程练习题答案]Java语言程序设计(基础篇)(进阶篇)第13、14、15、24、25、26、28、29、30、31章部分习题答案,奇数题和部分双数题是我自己做的,在此和大家分享(^_^~Chapter 13 Exercise 13.2 / 13.8 / 13.11import javax.swing.*;import java.awt.*;public class Exercise13_2 extends JFrame {// Create two buttonsprivate OvalButton jbtOk = new OvalButton("OK");private OvalButton jbtCancel = new OvalButton("Cancel");/** Default constructor */public Exercise13_2() {// Set the window titlesetTitle("Exercise13_2");// Set FlowLayout manager to arrange the componentsJava语言程序设计2 / 81// inside the framegetContentPane().setLayout(new FlowLayout());// Add buttons to the framegetContentPane().add(jbtOk);getContentPane().add(jbtCancel);}/** Main method */public static void main(String[] args) {Exercise13_2 frame = new Exercise13_2();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.pack();frame.setVisible(true);}}class OvalButton extends JButton {public OvalButton() {}public OvalButton(String text) {super(text);}protected void paintComponent(Graphics g) {// Draw an ovalsuper.paintComponent(g);g.drawOval(5, 5, getWidth() - 10, getHeight() - 10); }/** Override get method for preferredSize */public Dimension getPreferredSize() {return new Dimension(100, 50);}/** Override get method for minimumSize */public Dimension getMinimumSize() {return new Dimension(100, 50);}}Java语言程序设计3 / 81import java.awt.*;import javax.swing.*;public class Exercise13_8 extends JFrame {public static void main(String[] args) {JFrame frame = new Exercise13_8();frame.setSize(300, 300);frame.setTitle("Exercise13_8");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);}public Exercise13_8() {getContentPane().add(new OctagonPanel());}}class OctagonPanel extends JPanel {protected void paintComponent(Graphics g) {super.paintComponent(g);int xCenter = getWidth() / 2;int yCenter = getHeight() / 2;int radius =(int) (Math.min(getWidth(), getHeight()) * 0.4);// Create a Polygon objectPolygon polygon = new Polygon();// Add points to the polygonpolygon.addPoint(xCenter + radius, yCenter);polygon.addPoint((int)(xCenter + radius * Math.cos(2 *Math.PI / 8)),(int)(yCenter - radius * Math.sin(2 * Math.PI / 8)));polygon.addPoint((int)(xCenter + radius * Math.cos(2 * 2 * Math.PIJava语言程序设计4 / 81/ 8)),(int)(yCenter - radius * Math.sin(2 * 2 * Math.PI / 8)));polygon.addPoint((int)(xCenter + radius * Math.cos(3 * 2 * Math.PI/ 8)),(int)(yCenter - radius * Math.sin(3 * 2 * Math.PI / 8)));polygon.addPoint((int)(xCenter + radius * Math.cos(4 * 2 * Math.PI/ 8)),(int)(yCenter - radius * Math.sin(4 * 2 * Math.PI / 8)));polygon.addPoint((int)(xCenter + radius * Math.cos(5 * 2 * Math.PI/ 8)),(int)(yCenter - radius * Math.sin(5 * 2 * Math.PI / 8)));polygon.addPoint((int)(xCenter + radius * Math.cos(6 * 2 * Math.PI/ 8)),(int)(yCenter - radius * Math.sin(6 * 2 * Math.PI / 8))); polygon.addPoint((int)(xCenter + radius * Math.cos(7 * 2* Math.PI/ 8)),(int)(yCenter - radius * Math.sin(7 * 2 * Math.PI / 8)));// Draw the polygong.drawPolygon(polygon);}}import javax.swing.*;import java.awt.*;public class Exercise13_11 extends JFrame {public Exercise13_11(){add(new SquareFunction());}/*** @param args*/public static void main(String[] args) {Java语言程序设计5 / 81// TODO 自动生成方法存根Exercise13_11 frame = new Exercise13_11();frame.setTitle("Exercise13.11");frame.setSize(300,200);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);}}class SquareFunction extends JPanel {public SquareFunction(){}protected void paintComponent(Graphics g){super.paintComponent(g);g.drawLine(10, this.getHeight()-20, this.getWidth()-10,this.getHeight()-20);g.drawLine(this.getWidth()-30, this.getHeight()-15,this.getWidth()-10, this.getHeight()-20);g.drawLine(this.getWidth()-30, this.getHeight()-25,this.getWidth()-10, this.getHeight()-20);g.drawString("X", this.getWidth()-10,this.getHeight()-30);g.drawLine(this.getWidth()/2, 20, this.getWidth()/2,this.getHeight()-5);g.drawLine(this.getWidth()/2, 20, this.getWidth()/2-5,35);g.drawLine(this.getWidth()/2, 20, this.getWidth()/2+5,35);g.drawString("Y", this.getWidth()/2 + 10, 30);Polygon p = new Polygon();double scaleFactor = 0.01;for (int x=-100; x<=100; x++){p.addPoint(x+this.getWidth()/2,this.getHeight()-20-(int)(scaleFactor*x*x));}g.drawPolyline(p.xpoints, p.ypoints, p.npoints);}}Java语言程序设计6 / 81Chapter 14 Exercise 14.4 / 14.8 / 14.9package chapter14;import javax.swing.*;import java.awt.event.*;import java.awt.*;public class Exercise14_4 extends JFrame {public Exercise14_4(){MousePosition p = new MousePosition();add(p);}/*** @param args*/public static void main(String[] args) {// TODO 自动生成方法存根Exercise14_4 frame = new Exercise14_4();frame.setTitle("Exercise14.4");frame.setSize(300, 200);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setLocationRelativeTo(null);frame.setVisible(true);}static class MousePosi。

java语言程序设计课后习题答案

java语言程序设计课后习题答案

java语言程序设计课后习题答案Java语言程序设计课后习题答案Java语言是一种广泛应用于软件开发领域的编程语言,它具有简洁、可移植、面向对象等特点,因此在计算机科学与技术领域中得到了广泛的应用和推广。

学习Java语言程序设计是每个计算机科学与技术专业学生的必修课之一。

在学习过程中,老师通常会布置一些课后习题,以帮助学生巩固所学的知识。

本文将为大家提供一些Java语言程序设计课后习题的答案,希望对大家的学习有所帮助。

1. 编写一个Java程序,实现求阶乘的功能。

```javaimport java.util.Scanner;public class Factorial {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入一个正整数:");int n = scanner.nextInt();int result = 1;for (int i = 1; i <= n; i++) {result *= i;}System.out.println(n + "的阶乘为:" + result);}```2. 编写一个Java程序,实现判断一个数是否为素数的功能。

```javaimport java.util.Scanner;public class PrimeNumber {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入一个正整数:");int n = scanner.nextInt();boolean isPrime = true;for (int i = 2; i <= Math.sqrt(n); i++) {if (n % i == 0) {isPrime = false;break;}}if (isPrime) {System.out.println(n + "是素数");} else {System.out.println(n + "不是素数");}}```3. 编写一个Java程序,实现将一个字符串反转的功能。

java语言程序设计基础篇 复习题答案

java语言程序设计基础篇 复习题答案

java语言程序设计基础篇复习题答案
Java语言程序设计基础篇复习题答案
在学习Java语言程序设计基础篇的过程中,复习题是一个很好的方式来巩固所学知识。

下面是一些常见问题的答案,希望能够帮助大家更好地复习和理解Java语言程序设计基础篇的知识。

1. 什么是Java语言的特点?
答:Java语言具有简单、面向对象、分布式、多线程、动态、解释性等特点。

2. Java语言有哪些基本数据类型?
答:Java语言的基本数据类型包括整型、浮点型、字符型、布尔型等。

3. 什么是Java语言中的变量?
答:变量是用来存储数据的内存空间,它具有数据类型和名称。

4. Java语言中的运算符有哪些?
答:Java语言中的运算符包括算术运算符、关系运算符、逻辑运算符、位运算符等。

5. 什么是Java语言中的控制语句?
答:控制语句用于控制程序的执行流程,包括顺序结构、选择结构、循环结构等。

6. 什么是Java语言中的数组?
答:数组是一种用来存储多个相同类型数据的数据结构。

7. Java语言中的方法是什么?
答:方法是一段用来完成特定任务的代码,它可以被重复使用。

8. 什么是Java语言中的类和对象?
答:类是一种模板,用来描述对象的属性和行为;对象是类的实例,具有特定的属性和行为。

通过复习这些问题的答案,我们可以更好地理解和掌握Java语言程序设计基础篇的知识,为以后的学习和实践打下坚实的基础。

希望大家在学习Java语言程序设计基础篇的过程中能够不断努力,取得更好的成绩。

java语言程序设计基础篇复习题答案

java语言程序设计基础篇复习题答案

java语言程序设计基础篇复习题答案【篇一:《java语言程序设计基础教程》(龚永罡—陈昕)习题答案】txt>1.9练习思考题1、a,b,c2、d3、a,b 4 a 5、b6、开发与运行java程序需要经过的三个主要步骤为____ 、校验和___解释执行__ 。

7、如果一个java applet源程序文件只定义有一个类,该类的类名为myapplet,则类myapplet必须是类的子类并且存储该源程序文件的文件名为。

8、如果一个java applet程序文件中定义有3个类,则使用sun 公司的jdk编译器编译该源程序文件将产生3一个文件名与类名相同而扩展名为__class ______________ 的字节码文件。

11、编写一个简单的java应用程序,该程序在命令行窗口输出两行文字:“你好,很高兴学习java”和“we are students”。

解答:class myfirstjava{public static void main(string args[]){system・out.println(“你好,很高兴学习java”);system.out.println(“we are students”);}}第2章java基本的程序设计结构2.7练习思考题1、a, b, d2、C3、a4、b5、d6、d, f7、b8、d9、d10、a11、D12、a 13、B 14、c15、d16、a17、在java的基本数据类型中,char型采用unicode编码方案,每个unicode码占用字节内存空间,这样,无论是中文字符还是英文字符,都是占用字节内存空间。

18、设x = 2,则表达式( x + + )/3的值是。

19、若x = 5, y = 10,则x y和x = y的逻辑值分别为和。

20、设有数组定义:int myintarray[] = { 10, 20, 30, 40, 50, 60, 70 };则执行以下几个语句后的输出结果是:120。

《Java语言程序设计(基础篇)》(第10版 梁勇 著)第十九章练习题答案

《Java语言程序设计(基础篇)》(第10版 梁勇 著)第十九章练习题答案

《Java语言程序设计(基础篇)》(第10版梁勇著)第十九章练习题答案19.1class GenericStack<E> {public final static int INITIAL_SIZE = 16;private E[] elements;private int size;/** Construct a stack with the default initial capacity */public GenericStack() {this(INITIAL_SIZE);}/** Construct a stack with the specified initial capacity */public GenericStack(int initialCapacity) {elements = (E[])new Object[initialCapacity];}/** Push a new element into the top of the stack */public E push(E value) {if (size >= elements.length) {E[] temp = (E[])new Object[elements.length * 2];System.arraycopy(elements, 0, temp, 0, elements.length);elements = temp;}return elements[size++] = value;}/** Return and remove the top element from the stack */public E pop() {return elements[--size];}/** Return the top element from the stack */public E peek() {return elements[size - 1];}/** Exercise03_21 whether the stack is empty */public boolean isEmpty() {return size == 0;}/** Return the number of elements in the stack */public int getSize() {return size;}}19.2public class Exercise19_02 {public static void main(String[] args) {GenericStack<String> stack = new GenericStack<String>();stack.push("Tom");stack.push("George");stack.push("Peter");System.out.println(stack.getSize());System.out.println(stack.peek());System.out.println(stack.pop());System.out.println(stack.peek());}// GenericStack.java: Implementing a stack using inheritance static class GenericStack<E> extends java.util.ArrayList<E> { public boolean isEmpty() {return super.isEmpty();}public int getSize() {return size();}public Object peek() {return get(getSize() - 1);}public Object pop() {Object o = get(getSize() - 1);remove(getSize() - 1);return o;}public Object push(E o) {add(o);return o;}public int search(Object o) {return indexOf(o);}@Overridepublic String toString() {return"stack: " + toString();}}}19.3import java.util.ArrayList;public class Exercise19_03 {public static void main(String[] args) {ArrayList<Integer> list = new ArrayList<Integer>();list.add(14);list.add(24);list.add(14);list.add(42);list.add(25);ArrayList<Integer> newList = removeDuplicates(list);System.out.print(newList);}public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list) { ArrayList<E> result = new ArrayList<E>();for (E e: list) {if (!result.contains(e))result.add(e);}return result;}}19.4public class Exercise19_04 {public static <E extends Comparable<E>> void selectionSort(E[] list) {for (int i = 1; i < list.length; i++) {/** insert list[i] into a sorted sublist list[0..i-1] so thatlist[0..i] is sorted. */E currentElement = list[i];int k;for (k = i - 1; k >= 0 && list[k].compareTo(currentElement) > 0; k--) { list[k + 1] = list[k];}// Insert the current element into list[k+1]list[k + 1] = currentElement;}}}19.5public class Exercise19_05 {public static void main(String[] args) {Integer[] numbers = {1, 2, 3};System.out.println(max(numbers));String[] words = {"red", "green", "blue"};System.out.println(max(words));Circle[] circles = {new Circle(3), new Circle(2.9), new Circle(5.9)};System.out.println(max(circles));}static class Circle implements Comparable<Circle> {double radius;public Circle(double radius) {this.radius = radius;}@Overridepublic int compareTo(Circle c) {if (radius < c.radius)return -1;else if (radius == c.radius)return 0;elsereturn 1;}@Overridepublic String toString() {return"Circle radius: " + radius;}}public static <E extends Comparable<E>> E max(E[] list) { E max = list[0];for (int i = 1; i < list.length; i++) {if (pareTo(list[i]) < 0) {max = list[i];}}return max;}}19.6public class Exercise19_06 {public static void main(String[] args) {Integer[][] numbers = { {1, 2, 3}, {4, 4, 6}};System.out.println(max(numbers));}public static<E extends Comparable<E>> E max(E[][] list) { E max = list[0][0];for (int i = 1; i < list.length; i++) {for (int j = 1; j < list[i].length; j++) {if (pareTo(list[i][j]) < 0) {max = list[i][j];}}}return max;}}19.7public class Exercise19_07 {/** Use binary search to find the key in the list */ public static<E extends Comparable<E>>int binarySearch(E[] list, E key) {int low = 0;int high = list.length - 1;while (high >= low) {int mid = (low + high) / 2;if (pareTo(list[mid]) < 0) {high = mid - 1;}else if (key.equals(list[mid])) {return mid;}else {low = mid + 1;}}return -low - 1; // Now high < low}}19.8import java.util.ArrayList;public class Exercise19_08 {public static void main(String[] args) {ArrayList<Integer> list = new ArrayList<Integer>(); 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 <E> void shuffle(ArrayList<E> list) {for (int i = 0; i < list.size() - 1; i++) {int index = (int)(Math.random() * list.size());E temp = list.get(i);list.set(i, list.get(index));list.set(index, temp);}}}19.9import java.util.ArrayList;public class Exercise19_09 {public static void main(String[] args) {ArrayList<Integer> list = new ArrayList<Integer>();list.add(14);list.add(24);list.add(4);list.add(42);list.add(5);Exercise19_09.<Integer>sort(list);System.out.print(list);}/** Sort an array of comparable objects */public static <E extends Comparable<E>> void sort(ArrayList<E> list) { E currentMin;int currentMinIndex;for (int i = 0; i < list.size() - 1; i++) {// Find the minimum in the list[i+1..list.length-2]currentMin = list.get(i);currentMinIndex = i;for (int j = i + 1; j < list.size(); j++) {if (pareTo(list.get(j)) > 0) {currentMin = list.get(j);currentMinIndex = j;}}// Swap list[i] with list[currentMinIndex] if necessary;if (currentMinIndex != i) {list.set(currentMinIndex, list.get(i));list.set(i, currentMin);}}}}19.10import java.util.ArrayList;public class Exercise19_10 {public static void main(String[] args) {ArrayList<Integer> list = new ArrayList<Integer>();list.add(14);list.add(24);list.add(4);list.add(42);list.add(5);System.out.print(max(list));}public static <E extends Comparable<E>> E max(ArrayList<E> list) { E currentMax = list.get(0);for (int i = 1; i < list.size(); i++)if (pareTo(list.get(i)) < 0)currentMax = list.get(i);return currentMax;}}19.11import java.util.ArrayList;public class Exercise19_11 {public static void main(String[] args) {// Create two Complex arrays m1 and m2Complex[][] m1 = new Complex[3][3];Complex[][] m2 = new Complex[3][3];for (int i = 0; i < m1.length; i++)for (int j = 0; j < m1[0].length; j++) {m1[i][j] = new Complex(i + 1, j + 5);m2[i][j] = new Complex(i + 1, j + 6);}// Create an instance of ComplexMatrixComplexMatrix rationalMatrix = new ComplexMatrix();System.out.println("\nm1 + m2 is ");GenericMatrix.printResult(m1, m2, rationalMatrix.addMatrix(m1, m2), '+');System.out.println("\nm1 * m2 is ");GenericMatrix.printResult(m1, m2, rationalMatrix.multiplyMatrix(m1, m2), '*');}public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list) { ArrayList<E> result = new ArrayList<E>();for (E e: list) {if (!result.contains(e))result.add(e);}return result;}}class ComplexMatrix extends GenericMatrix<Complex> {@Override /** Add two rational numbers */protected Complex add(Complex r1, Complex r2) {return r1.add(r2);}@Override /** Multiply two rational numbers */protected Complex multiply(Complex r1, Complex r2) {return r1.multiply(r2);}@Override /** Specify zero for a Complex number */protected Complex zero() {return new Complex(0, 0);}}abstract class GenericMatrix<E> {/** Abstract method for adding two elements of the matrices */ protected abstract E add(E o1, E o2);/** Abstract method for multiplying two elements of the matrices */ protected abstract E multiply(E o1, E o2);/** Abstract method for defining zero for the matrix element */ protected abstract E zero();/** Add two matrices */public E[][] addMatrix(E[][] matrix1, E[][] matrix2) {// Check bounds of the two matricesif ((matrix1.length != matrix2.length) ||(matrix1[0].length != matrix2[0].length)) {throw new RuntimeException("The matrices do not have the same size");}E[][] result =(E[][])new Object[matrix1.length][matrix1[0].length];// Perform additionfor (int i = 0; i < result.length; i++)for (int j = 0; j < result[i].length; j++) {result[i][j] = add(matrix1[i][j], matrix2[i][j]);}return result;}/** Multiply two matrices */public E[][] multiplyMatrix(E[][] matrix1, E[][] matrix2) {// Check boundsif (matrix1[0].length != matrix2.length) {throw new RuntimeException("The matrices do not have compatible size");}// Create result matrixE[][] result =(E[][])new Object[matrix1.length][matrix2[0].length];// Perform multiplication of two matricesfor (int i = 0; i < result.length; i++) {for (int j = 0; j < result[0].length; j++) {result[i][j] = zero();for (int k = 0; k < matrix1[0].length; k++) {result[i][j] = add(result[i][j],multiply(matrix1[i][k], matrix2[k][j]));}}}return result;}/** Print matrices, the operator, and their operation result */ public static void printResult(Object[][] m1, Object[][] m2, Object[][] m3, char op) { for (int i = 0; i < m1.length; i++) {for (int j = 0; j < m1[0].length; j++)System.out.print(" " + m1[i][j]);if (i == m1.length / 2)System.out.print(" " + op + " ");elseSystem.out.print(" ");for (int j = 0; j < m2.length; j++)System.out.print(" " + m2[i][j]);if (i == m1.length / 2)System.out.print(" = ");elseSystem.out.print(" ");for (int j = 0; j < m3.length; j++) System.out.print(m3[i][j] + " ");System.out.println();}}}。

java基础篇第十版复习题答案

java基础篇第十版复习题答案

java基础篇第十版复习题答案1. 简述Java中基本数据类型及其大小。

答案:Java中的基本数据类型包括:byte(8位),short(16位),int(32位),long(64位),float(32位),double(64位),char(16位)和boolean(1位)。

2. 描述Java中类和对象的关系。

答案:类是对象的蓝图或模板,定义了对象的属性和方法。

对象是根据类创建的实例,具有类定义的属性和方法。

3. 说明Java中继承的概念及其特点。

答案:继承是Java中的一种机制,允许一个类(子类)继承另一个类(父类)的属性和方法。

特点包括代码重用、扩展性和实现多态。

4. 阐述Java中的接口是什么以及它的作用。

答案:接口在Java中是一种引用类型,它定义了一组方法规范,但不实现这些方法。

接口的作用是为不同的类提供统一的方法规范,实现多态。

5. 描述Java中异常处理的机制。

答案:Java中的异常处理机制包括try、catch和finally块。

try块用于捕获异常,catch块用于处理异常,finally块用于执行清理操作,无论是否发生异常。

6. 简述Java中集合框架的组成及其特点。

答案:Java集合框架主要由两大接口组成:Collection和Map。

Collection接口包括List、Set和Queue等子接口,用于存储单一元素。

Map接口用于存储键值对。

特点包括提供了统一的操作接口、支持泛型、实现了迭代器等。

7. 解释Java中多线程的概念及其实现方式。

答案:多线程是指程序中同时运行多个线程。

Java中实现多线程的方式包括继承Thread类和实现Runnable接口。

通过start()方法启动线程,线程执行run()方法。

8. 说明Java中垃圾回收机制的作用及其工作原理。

答案:垃圾回收机制的作用是自动回收不再使用的对象所占用的内存。

工作原理是通过引用计数或者标记-清除算法来识别无用对象,并释放其内存。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

《Java语言程序设计(基础篇)》(第10版梁勇著)第二十二章练习题答案22.1public class Exercise22_01 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Enter a string: ");String s = input.nextLine();System.out.println("Maximum consecutive substring is " + maxConsecutiveSortedSubstring(s));}/*** The worst-case complexity is O(n^2), where n is s.length(). Can you improve * the algorithm?*/public static String maxConsecutiveSortedSubstring(String s) {int[] maxConsecutiveLength = new int[s.length()];int current = 0;for (int i = 1; i < s.length(); i++) {if (s.charAt(i) <= s.charAt(i - 1)) { // next character is smallercurrent = i;} else {// s[current], s[current+1], ..., s[i-1] is a maximal increasing// sequencefor (int j = i - 1; j >= current; j--)maxConsecutiveLength[j]++;}}// maxConsecutiveLength[i] denotes the length of a max sequence starting at// index iint currentMaxLength = maxConsecutiveLength[0];int index = 0;for (int i = 0; i < s.length(); i++) {if (maxConsecutiveLength[i] > currentMaxLength) {currentMaxLength = maxConsecutiveLength[i];index = i;}}return s.substring(index, index + currentMaxLength + 1);}/* O(n) version, 9/21/2009 */public static String maxConsecutiveSortedSubstring1(String s) {int currentMaxLength = 1;int lastIndexOfMaxConsecutiveSortedSubstring = 0;int possibleMaxLength = 1;for (int i = 1; i < s.length(); i++) {if (s.charAt(i) > s.charAt(i - 1)) {if (lastIndexOfMaxConsecutiveSortedSubstring == i - 1) {// Add s(i) into the max consecutive substringcurrentMaxLength++;lastIndexOfMaxConsecutiveSortedSubstring++;} else {possibleMaxLength++;if (possibleMaxLength > currentMaxLength) {currentMaxLength = possibleMaxLength;lastIndexOfMaxConsecutiveSortedSubstring = i;possibleMaxLength = 1;}}}}return s.substring(lastIndexOfMaxConsecutiveSortedSubstring- currentMaxLength + 1, lastIndexOfMaxConsecutiveSortedSubstring + 1); }}22.1附加import javafx.application.Application;import javafx.geometry.Pos;import javafx.stage.Stage;import javafx.scene.Scene;import bel;import javafx.scene.image.Image;import javafx.scene.image.ImageView;import yout.BorderPane;import yout.Pane;import javafx.scene.paint.Color;import javafx.scene.shape.Line;import javafx.scene.shape.Rectangle;public class Exercise22_01Extra extends Application {public static final int SIZE = 8; // The size of the chess board// queens are placed at (i, queens[i])// -1 indicates that no queen is currently placed in the ith row// Initially, place a queen at (0, 0) in the 0th rowprivate int[] queens = {-1, -1, -1, -1, -1, -1, -1, -1};private Label lblStatus = new Label();// Display chess boardChessBoard chessBoard = new ChessBoard();int k = 0;@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {BorderPane pane = new BorderPane();Label lblMessage = new Label("Click the mouse to see the next move"); pane.setBottom(lblMessage);BorderPane.setAlignment(lblMessage, Pos.CENTER);pane.setTop(lblStatus);BorderPane.setAlignment(lblStatus, Pos.CENTER);pane.setCenter(chessBoard);// Create a scene and place it in the stageScene scene = new Scene(pane, 50 * SIZE, 55 * SIZE);primaryStage.setTitle("Exercise22_01"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagechessBoard.setOnMouseClicked(e -> {search();if (k == -1) {lblStatus.setText("No solution found");chessBoard.setOnMouseClicked(null);}else if (k == 8) {lblStatus.setText("A solution found");chessBoard.setOnMouseClicked(null);}chessBoard.repaint();});chessBoard.repaint();}/** Search for a solution */private boolean search() {// k - 1 indicates the number of queens placed so far// We are looking for a position in the kth row to place a queen if (k >= 0 && k < SIZE) {// Find a position to place a queen in the kth rowint j = findPosition(k);if (j < 0) {queens[k] = -1;k--; // back track to the previous row} else {queens[k] = j;k++;}}if (k == -1)return false; // No solutionelsereturn true; // A solution is found}public int findPosition(int k) {int start = queens[k] + 1; // Search for a new placementfor (int j = start; j < SIZE; j++) {if (isValid(k, j))return j; // (k, j) is the place to put the queen now}return -1;}/** Return true if a queen can be placed at (row, column) */ public boolean isValid(int row, int column) {for (int i = 1; i <= row; i++)if (queens[row - i] == column // Check column|| queens[row - i] == column - i // Check upleft diagonal|| queens[row - i] == column + i) // Check upright diagonal return false; // There is a conflictreturn true; // No conflict}class ChessBoard extends Pane {private Image queenImage = new Image("image/queen.jpg");ChessBoard() {setStyle("-fx-border-color: black");}double w = 400;double h = 400;public void repaint() {getChildren().clear();// Highlight the current rowRectangle rectangle = new Rectangle(0, k * h / SIZE,w, h / SIZE);rectangle.setFill(Color.YELLOW);getChildren().add(rectangle);// Paint the queensfor (int i = 0; i < SIZE; i++) {int j = queens[i]; // The position of the queen in row i System.out.println(j);System.out.println("getWidth " + w);ImageView imageView = new ImageView(queenImage);imageView.setX(j * w / SIZE);imageView.setY(i * h / SIZE);imageView.setFitWidth(w / SIZE);imageView.setFitHeight(h / SIZE);getChildren().add(imageView);}// Draw the horizontal and vertical linesfor (int i = 1; i < SIZE; i++) {getChildren().addAll(new Line(0, i * h / SIZE,w, i * h / SIZE), new Line(i * w / SIZE, 0,i * w / SIZE, h));}}}/*** 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);}}22.2public class Exercise22_02 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Enter a string: ");String s = input.nextLine();System.out.println("Maximum increasing ordered subsequence is " + maxSubstring(s));}/*** The worst-case complexity is O(n^2)*/public static String maxSubstring(String s) {// maxLength[i] stores the length of the max substring ending at index i int[] maxLength = new int[s.length()];// previous[i] stores the index of the previous element in the sequenece int[] previous = new int[s.length()];for (int i = 0; i < s.length(); i++) {previous[i] = -1;for (int j = i - 1; j >= 0; j--) {if (s.charAt(i) > s.charAt(j) &&maxLength[i] < maxLength[j] + 1) {maxLength[i] = maxLength[j] + 1;previous[i] = j;}}}// Find the largest subsequence length and ending indexint maxL = maxLength[0];int index = 0;for (int i = 1; i < s.length(); i++) {if (maxL < maxLength[i]) {maxL = maxLength[i];index = i;}}// Construct the subsequence by tracing through previous char[] chars = new char[maxL + 1];int i = maxL;while (index != -1) {chars[i--] = s.charAt(index);index = previous[index];}return new String(chars);}}22.3public class Exercise22_03 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Enter a string s1: ");String s1 = input.nextLine();System.out.print("Enter a string s2: ");String s2 = input.nextLine();int index = match1(s1, s2);if (index >= 0)System.out.println("matched at index " + index);elseSystem.out.println("unmatched");}/*** The worst-case complexity is O(n), where n is s.length() ** @param s String* @param pattern String* @return int*/public static int match(String s, String pattern) {int k = 0;for (int i = 0; i < s.length(); i++) {if (k == pattern.length())return i - pattern.length();else {if (s.charAt(i) == pattern.charAt(k))k++;elsek = 0;}}if (k == pattern.length())return s.length() - pattern.length();elsereturn -1;}/*** This is a brute-force approach, O(|s|*|pattern|))*/public static int match1(String s, String pattern) {for (int i = 0; i < s.length(); i++) {// Check if pattern matches si, si+1, ...int k = 0;for ( ; k < pattern.length(); k++) {if (s.charAt(i + k) != pattern.charAt(k))break;}if (k == pattern.length())return i;}return -1;}}22.4public class Exercise22_04 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in); System.out.print("Enter a string s1: ");String s1 = input.nextLine();System.out.print("Enter a string s2: ");String s2 = input.nextLine();int index = match(s1, s2);if (index >= 0)System.out.println("matched at index " + index);elseSystem.out.println("unmatched");// System.out.println(match("aerbbbcbbb", "bbcb"));}/*** The worst-case complexity is O(nk), where n is s.length() and k * is pattern.length()** @param s String* @param pattern String* @return int*/public static int match(String s, String pattern) {for (int p = 0; p < s.length(); p++) {int k = 0;for (int i = p; i < s.length(); i++) {if (k == pattern.length())return i - pattern.length();else {if (s.charAt(i) == pattern.charAt(k))k++;elsebreak;}}if (k == pattern.length())return s.length() - pattern.length();}return -1;}}22.5import java.util.Scanner;public class Exercise22_05 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a series of numbers ending with 0: ");int longestSequenceCount = 0;int longestSequenceValue = 0;int longestSequenceIndex = 0;int currentLongestSequenceCount = 1;int currentLongestSequenceValue = 0;int value;int index = 0;int previous = 0;do {value = input.nextInt();if (value == previous)currentLongestSequenceCount++;else if (currentLongestSequenceCount > longestSequenceCount) {longestSequenceCount = currentLongestSequenceCount;longestSequenceValue = currentLongestSequenceValue;longestSequenceIndex = index - currentLongestSequenceCount;currentLongestSequenceCount = 1; // Reset the countcurrentLongestSequenceValue = value; // Reset the value}previous = value;index++;}while (value != 0);System.out.println("The longest same number sequence starts at index " + longestSequenceIndex + " with " + longestSequenceCount+ " values of " + longestSequenceValue);}}22.6public class Exercise22_06 {public static void main(String[] args) {// Find the first 47 Fibonacci numbersfinal int INDEX = 47;int[] numbers = new int[INDEX];numbers[0] = 0;numbers[1] = 1;for (int i = 2; i < INDEX; i++) {numbers[i] = numbers[i - 1] + numbers[i - 2];}System.out.println("\t\t\t40\t41\t42\t43\t44\t45");System.out.println("-----------------------------------------------");System.out.print("Listing 23.2 GCD1");long[] executionTime = new long[6];for (int i = 40; i <= 45; i++) {long startTime = System.currentTimeMillis();gcd1(numbers[i], numbers[i + 1]);executionTime[i - 40] = System.currentTimeMillis() - startTime;}for (int i = 0; i <= 5; i++) {System.out.print("\t" + executionTime[i]);}System.out.print("\nListing 23.3 GCD2");for (int i = 40; i <= 45; i++) {long startTime = System.currentTimeMillis();gcd2(numbers[i], numbers[i + 1]);executionTime[i - 40] = System.currentTimeMillis() - startTime;}for (int i = 0; i <= 5; i++) {System.out.print("\t" + executionTime[i]);}}/** From Listing 21.2: Find gcd for intergers m and n */public static int gcd1(int m, int n) {int gcd = 1;if (m == n) return m;for (int k = 1; k <= m / 2 && k <= n / 2; k++) {if (m % k == 0 && n % k == 0)gcd = k;}return gcd;}/** From Listing 21.3: Find gcd for intergers m and n */public static int gcd2(int m, int n) {if (m % n == 0)return n;elsereturn gcd2(n, m % n);}}22.7import java.util.Arrays;import java.util.ArrayList;/** This program works, but the design is not good. Redesign it */ public class Exercise22_07 {public static void main(String[] args) {double[][] points = new double[1000][2];for (int i = 0; i < points.length; i++) {points[i][0] = Math.random() * 100;points[i][1] = Math.random() * 100;}long startTime = System.currentTimeMillis();Pair pair = closestPairBruteForce(points);System.out.println("shortest distance is " + pair.getDistance()); System.out.println(pair);long endTime = System.currentTimeMillis();System.out.println("Time spent on the brute-force algorithm is " + (endTime - startTime) + " milliseconds");startTime = System.currentTimeMillis();Pair closestPair = getClosestPair(points);System.out.println("shortest distance is " + closestPair.getDistance()); System.out.println(closestPair);endTime = System.currentTimeMillis();System.out.println("Time spent on the divide-and-conquer algorithm is " + (endTime - startTime) + " milliseconds");}/** Return the distance of the closest pair of points */public static Pair getClosestPair(double[][] points) {Point[] pointsOrderedOnX = new Point[points.length];for (int i = 0; i < pointsOrderedOnX.length; i++)pointsOrderedOnX[i] = new Point(points[i][0], points[i][1]);return getClosestPair(pointsOrderedOnX);}/** Return the distance of the closest pair of points */public static Pair getClosestPair(Point[] points) {Arrays.sort(points);// Locate the identical points if existsPair pair = checkIdentical(points);if (pair != null)return pair; // The distance between the identical points is 0Point[] pointsOrderedOnY = points.clone();Arrays.sort(pointsOrderedOnY, new CompareY());return distance(points, 0, points.length - 1, pointsOrderedOnY);}/** Locate the identical points if exist */public static Pair checkIdentical(Point[] pointsOrderedOnX) {Pair pair = new Pair();for (int i = 0; i < pointsOrderedOnX.length - 1; i++) {if (pointsOrderedOnX[i].compareTo(pointsOrderedOnX[i + 1]) == 0) {pair.p1 = pointsOrderedOnX[i];pair.p2 = pointsOrderedOnX[i + 1];return pair;}}return null;}/** Return the distance of the closest pair of points* in pointsOrderedOnX[low..high]. This is a recursive method.* pointsOrderedOnX and pointsOrderedOnY are not changed in the* subsequent recursive calls.*/public static Pair distance(Point[] pointsOrderedOnX,int low, int high, Point[] pointsOrderedOnY) {if (low >= high) // Zero or one point in the setreturn null;else if (low + 1 == high) {// Two points in the setPair pair = new Pair();pair.p1 = pointsOrderedOnX[low];pair.p2 = pointsOrderedOnX[high];return pair;}// Step 2int mid = (low + high) / 2;Pair pair1 = distance(pointsOrderedOnX, low, mid, pointsOrderedOnY);Pair pair2 = distance(pointsOrderedOnX, mid + 1, high, pointsOrderedOnY);double d;Pair pair = null;if (pair1 == null && pair2 == null) {d = Double.MAX_VALUE;} else if (pair1 == null) {d = pair2.getDistance();pair = pair2;} else if (pair2 == null) {d = pair1.getDistance();pair = pair1;} else {d = Math.min(pair1.getDistance(), pair2.getDistance());if (pair1.getDistance() <= pair2.getDistance())pair = pair1;elsepair = pair2;}// Obtain stripL and stripRArrayList<Point> stripL = new ArrayList<Point>();ArrayList<Point> stripR = new ArrayList<Point>();for (int i = 0; i < pointsOrderedOnY.length; i++)if (pointsOrderedOnY[i].x <= pointsOrderedOnX[mid].x&& pointsOrderedOnY[i].x >= pointsOrderedOnX[mid].x - d)stripL.add(pointsOrderedOnY[i]);elsestripR.add(pointsOrderedOnY[i]);// Step 3: Find the closest pair for a point in stripL and// a point in stripRdouble d3 = d;int r = 0;for (int i = 0; i < stripL.size(); i++) {while (r < stripR.size() && stripL.get(i).y > stripR.get(r).y + d)r++;// Compare a point in stripL with at most six points in stripRint r1 = r; // Start from r1 up in stripRwhile (r1 < stripR.size() && stripR.get(r1).y <= stripL.get(i).y + d) {if (d3 > distance(stripL.get(i), stripR.get(r1))) {d3 = distance(stripL.get(i), stripR.get(r1));pair.p1 = stripL.get(i);pair.p2 = stripR.get(r1);}r1++;}}return pair;}/** Compute the distance between two points p1 and p2 */public static double distance(Point p1, Point p2) {return distance(p1.x, p1.y, p2.x, p2.y);}/** Compute the distance between points (x1, y1) and (x2, y2) */public static double distance(double x1, double y1,double x2, double y2) {return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));}/** Define a class for a point with x- and y- coordinates */static class Point implements Comparable<Point> {double x;double y;Point(double x, double y) {this.x = x;this.y = y;}@Overridepublic int compareTo(Point p2) {if (this.x < p2.x)return -1;else if (this.x == p2.x) {// Secondary order on y-coordinatesif (this.y < p2.y)return -1;else if (this.y == p2.y)return 0;elsereturn 1;} elsereturn 1;}}/*** A comparator for comparing points on their y-coordinates. If y-coordinates * are the same, compare their x-coordinator.*/static class CompareY implements parator<Point> {public int compare(Point p1, Point p2) {if (p1.y < p2.y)return -1;else if (p1.y == p2.y) {// Secondary order on x-coordinatesif (p1.x < p2.x)return -1;else if (p1.x == p2.x)return 0;elsereturn 1;} elsereturn 1;}}/** A class to represent two points */public static class Pair {Point p1;Point p2;public double getDistance() {/* if (p1 == null || p2 == null)return Double.MAX_VALUE;else */return distance(p1, p2);}@Overridepublic String toString() {return"(" + p1.x + ", " + p1.y + ") and (" + p2.x + ", " + p2.y + ")"; }}public static Pair closestPairBruteForce(double[][] points) {Point[] p = new Point[points.length];for (int i = 0; i < p.length; i++)p[i] = new Point(points[i][0], points[i][1]);return closestPairBruteForce(p);}public static Pair closestPairBruteForce(Point[] points) {Pair pair = new Pair();if (points.length < 2)return null;// p1 and p2 are the indices in the points arraypair.p1 = points[0];pair.p2 = points[1];double shortestDistances = distance(pair.p1, pair.p2); // Initialize shortestDistances// Compute distance for every two pointsfor (int i = 0; i < points.length; i++) {for (int j = i + 1; j < points.length; j++) {double distance = distance(points[i], points[j]); // Find distanceif (distance < shortestDistances) {pair.p1 = points[i];pair.p2 = points[j];shortestDistances = distance; // Update shortestDistances}}}return pair;}}22.8import java.io.*;public class Exercise22_08 {final static int ARRAY_SIZE = 100000;public static void main(String[] args) throws Exception {// A list to hold prime numbersfinal long N = 100000002; // Find primes up to Nlong[] primeNumbers = new long[ARRAY_SIZE];long number; // A number to be tested for primenessRandomAccessFile inout =new RandomAccessFile("PrimeNumbers.dat", "rw");if (inout.length() == 0) {number = 1;}else {inout.seek(inout.length() - 8); // A long is 8 bytesnumber = inout.readLong(); // Get the last prime number in the file }int squareRoot = 1;// Repeatedly find prime numbersnewNumber:while (number <= N) {// Check if 2, 3, 4, ..., N is primenumber++;inout.seek(0);if (squareRoot * squareRoot < number) {squareRoot++;}while (inout.getFilePointer() < inout.length()) {int size = readNextBatch(primeNumbers, inout);// Exercise03_21 if number is primefor (int k = 0; k < size && primeNumbers[k] <= squareRoot; k++) {if (number % primeNumbers[k] == 0) { // If true, not primecontinue newNumber; // Exit the for loop}}}// Append a new prime number to the end of the fileinout.seek(inout.length());inout.writeLong(number);}inout.close();}public static int readNextBatch(long[] primeNumbers, RandomAccessFile inout) {int size = 0;try {while (inout.getFilePointer() < inout.length() && size < ARRAY_SIZE) { primeNumbers[size++] = inout.readLong();}}catch (Exception ex) {ex.printStackTrace();}return size;}}22.9import java.util.ArrayList;import java.util.Scanner;public class Exercise22_09 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("How many points are in the set? ");int numberOfPoints = input.nextInt();double[][] p = new double[numberOfPoints][2];System.out.print("Enter " + p.length + " points: ");for (int i = 0; i < p.length; i++)for (int j = 0; j < p[i].length; j++)p[i][j] = input.nextDouble();ArrayList<MyPoint> list = getConvexHull(p);System.out.print("The convex hull is ");for (int i = 0; i < list.size(); i++) {System.out.print("(" + list.get(i).x + ", " + list.get(i).y + ") "); }}static class MyPoint {double x, y;MyPoint(double x, double y) {this.x = x; this.y = y;}public boolean equals(Object o) {return x == ((MyPoint)o).x && y == ((MyPoint)o).y;}}/** Return the points that form a convex hull */public static ArrayList<MyPoint> getConvexHull(double[][] s) {// For efficiency, create an array of objectsMyPoint[] myPoints = new MyPoint[s.length];for (int i = 0; i < myPoints.length; i++)myPoints[i] = new MyPoint(s[i][0], s[i][1]);// Step 1MyPoint h0 = getRightmostLowestPoint(myPoints);ArrayList<MyPoint> H = new ArrayList<MyPoint>();H.add(h0);MyPoint t0 = h0;// Step 2 and Step 3while (true) {// Step 2MyPoint t1 = myPoints[0]; // Let t1 be s0for (int i = 1; i < myPoints.length; i++) {double status = whichSide(t0.x, t0.y, t1.x, t1.y, myPoints[i].x, myPoints[i].y);if (status > 0) // Right side of the line. Please note we are using the Java coordinate system. y increases downwardt1 = myPoints[i];else if (status == 0) {if (distance(s[i][0], s[i][1], t0.x, t0.y) > distance(t1.x, t1.y, t0.x, t0.y))t1 = myPoints[i];}}// Step 3if (t1.equals(h0)) // (t1.x == h0.x && t1.y == h0.y)break; // A convex hull is foundelse {H.add(t1);t0 = t1;}}return H;}/** Return the rightmost lowest point in S */private static MyPoint getRightmostLowestPoint(MyPoint[] p) {int rightMostIndex = 0;double rightMostX = p[0].x;double rightMostY = p[0].y;for (int i = 1; i < p.length; i++) {if (rightMostY < p[i].y) {rightMostY = p[i].y;rightMostX = p[i].x;rightMostIndex = i;}else if (rightMostY == p[i].y && rightMostX < p[i].x) {rightMostX = p[i].x;rightMostIndex = i;}}return p[rightMostIndex];}public static double distance(double x1, double y1, double x2, double y2) { return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));}static double whichSide(double x0, double y0, double x1, double y1, double x2, double y2) {return (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0);}}22.10import java.io.*;public class Exercise22_10 {public static void main(String[] args) throws Exception {int count = 0; // Count the number of prime numbersDataInputStream input =new DataInputStream(new BufferedInputStream(new FileInputStream("Exercise22_07.dat")));long[] limits = {10,100,1000,10000,100000,1000000,10000000,100000000,1000000000,10000000000L,100000000000L,1000000000000L,10000000000000L,100000000000000L,1000000000000000L,10000000000000000L,100000000000000000L,1000000000000000000L};int k = 0;while (input.available() > 0) {if (input.readLong() > limits[k]) {System.out.println("Number of prime number <= " + limits[k] + " is " + count);k++;if (k == limits.length) break;}count++;}input.close();System.out.println("Total number of prime numbers found: " +count);}}22.11import java.util.ArrayList;import java.util.Collections;import java.util.Scanner;public class Exercise22_11 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("How many points are in the set? ");int numberOfPoints = input.nextInt();double[][] p = new double[numberOfPoints][2];System.out.print("Enter " + p.length + " points: ");for (int i = 0; i < p.length; i++)for (int j = 0; j < p[i].length; j++)p[i][j] = input.nextDouble();ArrayList<MyPoint> list = getConvexHull(p);System.out.print("The convex hull is ");for (int i = 0; i < list.size(); i++) {System.out.print("(" + list.get(i).x + ", " + list.get(i).y + ") "); }}/** Return the points that form a convex hull */public static ArrayList<MyPoint> getConvexHull(double[][] points) {// Create MyPoint objects for pointsArrayList<MyPoint> p = new ArrayList<MyPoint>();for (int i = 0; i < points.length; i++)p.add(new MyPoint(points[i][0], points[i][1]));placeP0(p);for (int i = 0; i < points.length; i++)p.get(i).setRightMostLowestPoint(p.get(0));Collections.sort(p);p = discardTies(p); // If two points have the same angle, discard the one that is closer to p0if (p.size() < 3)return null;ArrayList<MyPoint> stack = new ArrayList<MyPoint>(); // We use ArrayList rather than java.util.Stack, because the algorithm needs to access the top two elementsstack.add(p.get(0));stack.add(p.get(1));stack.add(p.get(2));int i = 3;while (i < p.size()) {MyPoint t2 = stack.get(stack.size() - 1);MyPoint t1 = stack.get(stack.size() - 2);if(whichSide(t1.x, t1.y, t2.x, t2.y, p.get(i).x, p.get(i).y) >= 0) { // on the right of the line from t1 to t2// pop the top element off the stack。

相关文档
最新文档