《Java语言程序设计(基础篇)》(第10版 梁勇 著)第八章练习题答案
java语言程序设计基础篇 复习题答案
java语言程序设计基础篇复习题答案Java语言程序设计基础篇复习题答案Java语言是一种广泛应用于软件开发领域的高级编程语言,具有跨平台、面向对象、简单易学等特点。
在学习Java语言的过程中,复习题是一种非常有效的巩固知识的方式。
本文将为大家提供一些Java语言程序设计基础篇的复习题答案,希望能够帮助大家更好地理解和掌握Java语言。
1. 以下代码的输出结果是什么?```javapublic class Test {public static void main(String[] args) {int x = 5;int y = 10;System.out.println("x + y = " + (x + y));System.out.println("x - y = " + (x - y));System.out.println("x * y = " + (x * y));System.out.println("x / y = " + (x / y));}}```答案:```x + y = 15x - y = -5x * y = 50x / y = 0```2. 以下代码的输出结果是什么?```javapublic class Test {public static void main(String[] args) { int x = 5;int y = 10;boolean result = (x > y) && (x != y); System.out.println(result);}}```答案:```false```3. 以下代码的输出结果是什么?```javapublic class Test {public static void main(String[] args) {int x = 5;int y = 10;boolean result = (x < y) || (x == y);System.out.println(result);}}```答案:```true```4. 以下代码的输出结果是什么?```javapublic class Test {public static void main(String[] args) {int x = 5;int y = 10;if (x > y) {System.out.println("x is greater than y"); } else if (x < y) {System.out.println("x is less than y");} else {System.out.println("x is equal to y");}}}```答案:```x is less than y```5. 以下代码的输出结果是什么?```javapublic class Test {public static void main(String[] args) {int x = 5;int y = 10;int max = (x > y) ? x : y;System.out.println("The maximum value is: " + max); }}```答案:```The maximum value is: 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版梁勇著)第九章练习题答案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语言程序设计第8章习题参考答案.docx
习题八参考答案1.什么是组件?什么是容器?并说明各自的作用。
答:从实现角度来看,组件(Component)是构成GUI的基本要素,作用是通过对不同事件的响应来完成和用户的交互或组件之间的交互;容器是能容纳和排列组件的对象,如Applet> Panel (面板)、Frame (窗口)等,作用就是放置组件并控制组件位置。
2.简述Swing组件的优点。
答:Swing是在AWT基础上扩展而来的,提供了非常丰富的组件,远远多于AWT,并且引入了新的概念和性能,这使得基于Swing开发GUI应用程序比直接使用AWT开发更为灵活、方便、效率高,而且能设计出更优美的、感受更好的GUI。
3.简述容器的概念,结合8.4.7小节的内容,解释什么是应用程序的主框架?答:容器是用来容纳其他组件和容器的特殊组件,是由容器类(Container类)创建的对象。
在Java语言中,容器类是组件类(组件类Component类)的一个子类,具有组件的所有性质。
在AWT 技术中,容器类由java. awt包提供,主要包括面板类Panel、窗口类Window、结构类Frame、对话框类Dialog等。
在Swing技术中,容器类由javax. swing包提供,并可分为如下三类:>顶层容器:JFramc. JApplet. JDialog、JWindow;>中间容器:JPanel、JScrollPane^ JSplitPane、JDesktopPaneJToolBar;特殊容器:在GUI上起特殊作用的中间层,如J Interna IFrame、JLayeredPane、 JRootPaneo 应用程序的主框架由可以容纳应用程序各种组件的顶层容器创建,除了负责组件的管理外,通常还提供最大化、最小化、关闭按钮等,实现应用程序展现方式以及关闭等。
4.总结JFrame的使用要点,并说明内容面板的作用。
答:JFrame类包含很多设置窗体的方法,可以用setTitle(String tille)方法设置窗体标题,用setBounds(inl x,int y,int width,int height)方法设置窗体显示的位置及大小,用setVisable (Boolean b)方法设置可见与否(默认不可见)。
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语言程序设计基础篇复习题答案一、选择题1. Java语言属于以下哪种类型的编程语言?A. 编译型语言B. 解释型语言C. 汇编语言D. 机器语言答案:B2. 下面哪个是Java语言的正确数据类型?A. intB. floatC. doubleD. 所有选项都是答案:D3. Java程序的入口点是哪一个方法?A. main()B. start()C. run()D. execute()答案:A4. Java中,哪个关键字用于定义类?A. classB. typeC. defineD. struct答案:A5. Java中的异常处理是通过什么机制实现的?A. 继承B. 多态C. 接口D. 异常处理语句答案:D二、填空题1. Java语言是一种_________语言,它支持_________和_________。
答案:面向对象;封装;继承2. 在Java中,所有的类都是从_________类继承而来的。
答案:Object3. Java程序的执行流程是从_________方法开始的。
答案:main4. Java中的数组是_________的。
答案:固定长度5. Java语言支持_________和_________两种类型的异常。
答案:编译时异常;运行时异常三、简答题1. 请简述Java语言的特点。
答案:Java语言是一种面向对象的编程语言,具有跨平台性、安全性高、健壮性、多线程等特点。
2. 请解释Java中的“垃圾回收”机制。
答案:Java的垃圾回收机制是一种自动内存管理技术,它能够自动回收不再使用的对象所占用的内存,防止内存泄漏。
四、编程题1. 编写一个Java程序,实现计算两个整数的和。
```javapublic class SumCalculator {public static void main(String[] args) {int num1 = 5;int num2 = 10;int sum = num1 + num2;System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum);}}```2. 编写一个Java程序,实现打印一个字符串的所有字符。
Java语言程序设计(基础篇)第10版习题答案Chapter9-1
Java语⾔程序设计(基础篇)第10版习题答案Chapter9-1(矩形类 Rectangle)遵照9.2节中 Circle 类的例⼦,设计⼀个名为 Rectangle 的类表⽰矩形。
这个类包括:两个名为 width 和 height 的 double 型数据域,它们分别表⽰矩形的宽和⾼。
width 和 height 的默认值都为1。
创建默认矩形的⽆参构造⽅法⼀个创建 width 和 height 为指定值的矩形的构造⽅法。
⼀个名为 getArea() 的⽅法返回这个矩形的⾯积。
⼀个名为 getPerimeter() 的⽅法返回周长。
画出该矩形的 UML 图并实现这个类。
编写⼀个测试程序,创建两个 Rectangle 对象——⼀个矩形的宽为 4 ⽽⾼为 40,另⼀个矩形的宽为3.5 ⽽⾼为 35.9 。
按照这个顺序显⽰每个矩形的宽、⾼、⾯积、周长。
程序代码:public class Rectangle {private double width;private double height;public Rectangle(){width=1.0;height=1.0;}public Rectangle(double width,double height) {this.width=width;this.height=height;}public double getWidth() {return width;}public double getHeight() {return height;}public double getArea() {return width*height;}public double getPerimeter() {return 2*(width+height);}public static void main(String[] args) {// TODO Auto-generated method stubRectangle t1=new Rectangle(4,40);Rectangle t2=new Rectangle(3.5,35.9);System.out.println("width:"+t1.getWidth()+" height:"+t1.getHeight()+" Area:"+t1.getArea()+" Per:"+t1.getPerimeter());System.out.println("width:"+t2.getWidth()+" height:"+t2.getHeight()+" Area:"+t2.getArea()+" Per:"+t2.getPerimeter());}}运⾏结果:width:4.0 height:40.0 Area:160.0 Per:88.0width:3.5 height:35.9 Area:125.64999999999999 Per:78.8。
java语言程序设计基础篇第十版练习答案精编
j a v a语言程序设计基础篇第十版练习答案精编Document number:WTT-LKK-GBB-08921-EIGG-2298601import class Exercise14_01 extendsApplication {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}02import class Exercise14_02 extends Application {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}03import class Exercise14_03 extends Application {@Override One is to use the hint in the book.ArrayList<Integer> list = new ArrayList<>(); for (int i = 1; i <= 52; i++) {(i);}HBox pane = new HBox(5);;().add(new ImageView("image/card/" + (0) +".png"));().add(new ImageView("image/card/" + (1) +".png"));().add(new ImageView("image/card/" + (2) +".png"));Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}04import class Exercise14_04 extends Application {@Override dd(txt);}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}05import class Exercise14_05 extends Application {@Override dd(txt);}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}05import class Exercise14_05 extends Application {@Override dd(txt);}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}06import class Exercise14_06 extends Application {@Override dd(rectangle);}}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}07import class Exercise14_07 extends Application {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}08import class Exercise14_08 extends Application {@Override ng"), j, i);}}Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}09import class Exercise14_09 extends Application {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}class FanPane extends Pane {double radius = 50;public FanPane() {Circle circle = new Circle(60, 60, radius);;;getChildren().add(circle);Arc arc1 = new Arc(60, 60, 40, 40, 30, 35);; ddAll(arc1, arc2, arc3, arc4);}}10import class Exercise14_10 extends Application {@Override ddAll, ;Arc arc2 = new Arc(100, 140, 50, 20, 180, 180); ;;().addAll(ellipse, arc1, arc2,new Line(50, 40, 50, 140), new Line(150, 40, 150, 140));Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}11import class Exercise14_11 extends Application {@Override ddAll(circle, ellipse1, ellipse2,circle1, circle2, line1, line2, line3, arc);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}12import class Exercise14_12 extends Application {@Override ddAll(r1, text1, r2, text2, r3, text3, r4, text4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}13import class Exercise14_13 extends Application {@Override ddAll(arc1, text1, arc2, text2, arc3, text3, arc4, text4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}14import class Exercise14_14 extends Application {@Override ddAll(r1, r2, line1, line2, line3, line4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}15import class Exercise14_15 extends Application {@Override ddAll(polygon, text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16import class Exercise14_16 extends Application {@Override ind().divide(3));().bind());().bind().divide(3));;Line line2 = new Line(0, 0, 0, 0);().bind().multiply(2).divide(3));().bind());().bind().multiply(2).divide(3));;Line line3 = new Line(0, 0, 0, 0);().bind().divide(3));().bind().divide(3));().bind());;Line line4 = new Line(0, 0, 0, 0);().bind().multiply(2).divide(3));().bind().multiply(2).divide(3));().bind());;().addAll(line1, line2, line3, line4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}17import class Exercise14_17 extends Application {@Override ddAll(arc, line1, line2, line3, circle, line4, line5, line6, line7, line8);Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}18import class Exercise14_18 extends Application {@Override ddAll(polyline, line1, line2,line3, line4, line5, line6, text1, text2);Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}19import class Exercise14_19 extends Application {@Override ddAll(polyline1, polyline2, line1,line2,line3, line4, line5, line6, text1, text2,text3,text4, text5, text6, text7);Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}20import class Exercise14_20 extends Application {@Override dd(new Line(x1, y1, x2, y2));dd(new Line(x2, y2, (x2 + (arctan + set45) * arrlen)),((y2)) + (arctan + set45) * arrlen)));().add(new Line(x2, y2, (x2 + (arctan - set45) * arrlen)),((y2)) + (arctan - set45) * arrlen)));}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}21import class Exercise14_21 extends Application {@Override istance(x2, y2) + "");().addAll(circle1, circle2, line, text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}22import class Exercise14_22 extends Application {@Override ddAll(circle1, circle2, line, text1, text2);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}23import class Exercise14_23 extends Application {@Override ddAll(r1, r2, text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}24import class Exercise14_24 extends Application {@Override ddAll(polygon, new Circle(x5, y5, 10), text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}25import class Exercise14_25 extends Application {@Override ddAll(circle, polygon);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}26import class Exercise14_26 extends Application {@Override ddAll(clock1, clock2);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}27import class Exercise14_27 extends Application {@OverrideNot needed for running from the command line. */public static void main(String[] args) {launch(args);}}class DetailedClockPane extends Pane {private int hour;private int minute;private int second;lear();getChildren().addAll(circle, sLine, mLine, hLine);dd(new Line(xOuter, yOuter, xInner, yInner));}dd(text);}}}28import class Exercise14_28 extends Application {@OverrideNot needed for running from the command line.*/public static void main(String[] args) {launch(args);}}class ClockPaneWithBooleanProperties extends Pane { private int hour;private int minute;private int second;private boolean hourHandVisible = true;private boolean minuteHandVisible = true; private boolean secondHandVisible = true;public boolean isHourHandVisible() {return hourHandVisible;}public void setHourHandVisible(boolean hourHandVisible) {= hourHandVisible;paintClock();}public boolean isMinuteHandVisible() {return minuteHandVisible;}public void setMinuteHandVisible(boolean minuteHandVisible) {= minuteHandVisible;paintClock();}public boolean isSecondHandVisible() {return secondHandVisible;public void setSecondHandVisible(boolean secondHandVisible) {= secondHandVisible;paintClock();}lear();getChildren().addAll(circle, t1, t2, t3, t4);if (secondHandVisible) {getChildren().add(sLine);}if (minuteHandVisible) {getChildren().add(mLine);}if (hourHandVisible) {getChildren().add(hLine);}}}import class Exercise14_29 extends Application {final static double HGAP = 20;final static double VGAP = 20;final static double RADIUS = 5;final static double LENGTH_OF_SLOTS = 40;final static double LENGTH_OF_OPENNING = 15;final static double Y_FOR_FIRST_NAIL = 50;final static double NUMBER_OF_SLOTS = 9;final static double NUMBER_OF_ROWS =NUMBER_OF_SLOTS - 2;@Override dd(c);}}dd(new Line(x, y, x, y + LENGTH_OF_SLOTS)); }dd(new Line(centerX - (NUMBER_OF_ROWS - 1) * HGAP / 2 - HGAP,y + LENGTH_OF_SLOTS, centerX -(NUMBER_OF_ROWS - 1) * HGAP / 2 + NUMBER_OF_ROWS * HGAP,y + LENGTH_OF_SLOTS));dd(new Line(centerX + HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX - (NUMBER_OF_ROWS - 1) * HGAP / 2 + NUMBER_OF_ROWS * HGAP, y));().add(new Line(centerX - HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX - (NUMBER_OF_ROWS - 1) * HGAP / 2 - HGAP, y));dd(new Line(centerX - HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX - HGAP / 2, Y_FOR_FIRST_NAIL - LENGTH_OF_OPENNING));().add(new Line(centerX + HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX + HGAP / 2, Y_FOR_FIRST_NAIL - LENGTH_OF_OPENNING));Not needed for running from the command line.*/public static void main(String[] args) { launch(args);}}。
(完整版)Java语言程序设计(基础篇)原书第十版梁勇著第一章答案
第一章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语言程序设计-基础篇》答案-第08章
8.19 答: (a) 输出结果如下:
j is 3 i is 1 (b) 输出结果如下: i is 0 j is 4 i is 5 j is 4
8.20 答:(略)
8.21 答:结果是
z对 z错 z对 z对 z错 z错 z对 z错 z错
网 案 答 后 课
a 改为:return super.findArea() * length; hd 8.4 答:(略),自行查阅课本。 .k 8.5 答:每个类均有。
w 从公共父类 ng.Object 继承而来。 ww 创建对象后可以通过对象引用直接调用它们。 网 8.6 答:输出结果如下:
B’s constructor is invoked
1
7
网
案 8.12 答:无修饰符(包作用域)。说明:该题应为“应该在一个类的成员前面……”。
答 8.13 答:protected 修饰符。说明:该题应为“应该在一个类的成员前面……”。
后 8.14 答:类 B 能正常编译。 课 8.15 答:?处应该 protected,当然 public 是一定可以的。
案 A’s constructor is invoked 答 调用 new A(3)时,会调用 Object 的无参构造方法。 后 8.7 答:结果如下: 课 对(a)中的类 Circle,Test 类主方法输出 false;
对(b)中的类 Circle,Test 类主方法输出 false;
原因:
(a)中的 equals 方法,由于参数类型与其父类 Object 的 equals 方法 不同,所以没有形成覆盖,则在 Test 类方法中调用的是父类 Object 的 equals 方法,因此不能正确比较 2 个圆对象是否相等地。 (b)中的 equals 方法,形成了对父类 Object 的 equals 方法的覆盖, 则在 Test 类方法中调用的是子类 Circle 的 equals 方法,因此能正 确比较。
《Java语言程序设计(基础篇)》(第10版 梁勇 著)第十六章练习题答案
《Java语言程序设计(基础篇)》(第10版梁勇著)第十六章练习题答案16.1import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.RadioButton;import javafx.scene.control.ToggleGroup;import yout.BorderPane;import yout.HBox;import yout.Pane;import javafx.scene.paint.Color;import javafx.scene.text.Font;import javafx.scene.text.Text;import javafx.stage.Stage;public class Exercise16_01 extends Application {private double paneWidth = 500;private double paneHeight = 150;@Override // Override the start method in the Application class public void start(Stage primaryStage) {Text text = new Text(20, 40, "Programming is fun");text.setFont(new Font("Times", 20));Pane paneForText = new Pane();paneForText.getChildren().add(text);paneForText.setStyle("-fx-border-color: gray");RadioButton rbRed = new RadioButton("Red");RadioButton rbYellow = new RadioButton("Yellow");RadioButton rbBlack = new RadioButton("Black");RadioButton rbOrange = new RadioButton("Orange");RadioButton rbGreen = new RadioButton("Green");ToggleGroup group = new ToggleGroup();rbRed.setToggleGroup(group);rbYellow.setToggleGroup(group);rbBlack.setToggleGroup(group);rbBlack.setSelected(true);rbOrange.setToggleGroup(group);rbGreen.setToggleGroup(group);HBox hBox = new HBox(5);hBox.getChildren().addAll(rbRed, rbYellow, rbBlack, rbOrange, rbGreen); hBox.setAlignment(Pos.CENTER);Button btLeft = new Button("<=");Button btRight = new Button("=>");HBox hBoxForButtons = new HBox(5);hBoxForButtons.getChildren().addAll(btLeft, btRight);hBoxForButtons.setAlignment(Pos.CENTER);BorderPane borderPane = new BorderPane();borderPane.setTop(hBox);borderPane.setCenter(paneForText);borderPane.setBottom(hBoxForButtons);// Create a scene and place it in the stageScene scene = new Scene(borderPane, paneWidth, paneHeight + 40);primaryStage.setTitle("Exercise16_01"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagerbRed.setOnAction(e -> text.setStroke(Color.RED));rbYellow.setOnAction(e -> text.setStroke(Color.YELLOW));rbBlack.setOnAction(e -> text.setStroke(Color.BLACK));rbOrange.setOnAction(e -> text.setStroke(Color.ORANGE));rbGreen.setOnAction(e -> text.setStroke(Color.GREEN));btLeft.setOnAction(e -> text.setX(text.getX() - 1));btRight.setOnAction(e -> text.setX(text.getX() + 1));}/*** 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);}}16.1附加import javafx.application.Application;import javafx.scene.Scene;import yout.*;import javafx.scene.paint.Color;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.geometry.Pos;public class Exercise16_01Extra extends Application {final static double PANEL_WIDTH = 400;final static double PANEL_HEIGHT = 140;@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {GridPane paneForOriginal = new GridPane();GridPane paneForInversed = new GridPane();TextField[][] tfOriginal = new TextField[3][3];TextField[][] tfInversed = new TextField[3][3];for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {paneForOriginal.add(tfOriginal[i][j] = new TextField(), j, i); tfOriginal[i][j].setPrefColumnCount(4);paneForInversed.add(tfInversed[i][j] = new TextField(), j, i); tfInversed[i][j].setPrefColumnCount(4);}}BorderPane p1 = new BorderPane();p1.setCenter(paneForOriginal);p1.setTop(new Label("Original Matrix"));BorderPane p2 = new BorderPane();p2.setCenter(paneForInversed);final Label lblStatus = new Label("Inversed Matrix");p2.setTop(lblStatus);HBox hBox = new HBox(5);hBox.getChildren().addAll(p1, p2);BorderPane pane = new BorderPane();pane.setCenter(hBox);Button btGetInverse = new Button("Get Inverse");pane.setBottom(btGetInverse);BorderPane.setAlignment(btGetInverse, Pos.CENTER);Scene scene = new Scene(pane, PANEL_WIDTH, PANEL_HEIGHT);primaryStage.setTitle("Exercise16_01"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagebtGetInverse.setOnAction(e -> {double[][] A = new double[3][3];for (int i = 0; i < 3; i++)for (int j = 0; j < 3; j++) {A[i][j] = Double.parseDouble(tfOriginal[i][j].getText()); }double[][] inverseA = Exercise08_03Extra.inverse(A);if (inverseA == null)lblStatus.setText("Invered matrix: No inverse matrix");else {for (int i = 0; i < 3; i++)for (int j = 0; j < 3; j++) {tfInversed[i][j].setText(inverseA[i][j] + "");}}});}/*** 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);}}16.2import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.CheckBox;import javafx.scene.control.RadioButton;import javafx.scene.control.ToggleGroup;import yout.BorderPane;import yout.HBox;import yout.StackPane;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.shape.Ellipse;import javafx.scene.shape.Rectangle;import javafx.stage.Stage;public class Exercise16_02 extends Application {private double paneWidth = 500;private double paneHeight = 150;@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {StackPane pane = new StackPane();Circle circle = new Circle(20, 20, 50);circle.setStroke(Color.BLACK);circle.setFill(Color.WHITE);Rectangle rectangle = new Rectangle(20, 20, 80, 50);rectangle.setStroke(Color.BLACK);Ellipse ellipse = new Ellipse(20, 20, 50, 70);ellipse.setStroke(Color.BLACK);pane.setStyle("-fx-border-color: gray");pane.getChildren().add(circle);RadioButton rbCircle = new RadioButton("Circle");RadioButton rbRectangle = new RadioButton("Rectangle");RadioButton rbEllipse = new RadioButton("Ellipse");CheckBox chkFill = new CheckBox("Fill");ToggleGroup group = new ToggleGroup();rbCircle.setToggleGroup(group);rbCircle.setSelected(true);rbRectangle.setToggleGroup(group);rbEllipse.setToggleGroup(group);HBox hBox = new HBox(5);hBox.getChildren().addAll(rbCircle, rbRectangle, rbEllipse, chkFill); hBox.setAlignment(Pos.CENTER);BorderPane borderPane = new BorderPane();borderPane.setCenter(pane);borderPane.setBottom(hBox);// Create a scene and place it in the stageScene scene = new Scene(borderPane, paneWidth, paneHeight + 40); primaryStage.setTitle("Exercise16_02"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagerbCircle.setOnAction(e -> {pane.getChildren().clear();pane.getChildren().add(circle);if (chkFill.isSelected()) {circle.setFill(Color.BLACK);}else {circle.setFill(Color.WHITE);}});rbRectangle.setOnAction(e -> {pane.getChildren().clear();pane.getChildren().add(rectangle);if (chkFill.isSelected()) {rectangle.setFill(Color.BLACK);}else {rectangle.setFill(Color.WHITE);}});rbEllipse.setOnAction(e -> {pane.getChildren().clear();pane.getChildren().add(ellipse);if (chkFill.isSelected()) {ellipse.setFill(Color.BLACK);}else {ellipse.setFill(Color.WHITE);}});chkFill.setOnAction(e -> {if (chkFill.isSelected()) {circle.setFill(Color.BLACK);rectangle.setFill(Color.BLACK);ellipse.setFill(Color.BLACK);}else {circle.setFill(Color.WHITE);rectangle.setFill(Color.WHITE);ellipse.setFill(Color.WHITE);}});}/*** 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);}}16.2附加import javafx.application.Application;import javafx.scene.Scene;import yout.*;import javafx.scene.paint.Color;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.geometry.Pos;public class Exercise16_02Extra extends Application {final static double PANEL_WIDTH = 400;final static double PANEL_HEIGHT = 140;@Override // Override the start method in the Application class public void start(Stage primaryStage) {GridPane paneForOriginal = new GridPane();GridPane paneForInversed = new GridPane();TextField[][] tfA = new TextField[3][3];TextField[] tfB = new TextField[3];for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {tfA[i][j] = new TextField();tfA[i][j].setPrefColumnCount(4);}tfB[i] = new TextField();tfB[i].setPrefColumnCount(4);}HBox[] hBoxes = new HBox[3];for (int i = 0; i < 3; i++) {hBoxes[i] = new HBox(5);hBoxes[i].getChildren().addAll(tfA[i][0], new Label("x"), tfA[i][1], new Label("y"), tfA[i][2], new Label("z = "), tfB[i]);}VBox vBox = new VBox(5);vBox.getChildren().addAll(hBoxes[0], hBoxes[1], hBoxes[2]);HBox hBox = new HBox(5);Label lblStatus = new Label();Button btSolveEquation = new Button("Solve Equation");hBox.getChildren().addAll(btSolveEquation, lblStatus);BorderPane pane = new BorderPane();pane.setCenter(vBox);pane.setBottom(hBox);Scene scene = new Scene(pane, PANEL_WIDTH, PANEL_HEIGHT);primaryStage.setTitle("Exercise16_02"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagebtSolveEquation.setOnAction(e -> {double[][] A = new double[3][3];double[] B = new double[3];for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {A[i][j] = Double.parseDouble(tfA[i][j].getText());}B[i] = Double.parseDouble(tfB[i].getText());}double[] result = Exercise08_02Extra.getSolution(A, B);if (result == null)lblStatus.setText("No solutions");elselblStatus.setText("Solution is x = "+ result[0] + ", y is = "+ result[1]+ ", and z is = " + result[2]);});}/*** 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);}}16.3import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.RadioButton;import javafx.scene.control.ToggleGroup;import yout.BorderPane;import yout.HBox;import yout.Pane;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.shape.Rectangle;import javafx.stage.Stage;public class Exercise16_03 extends Application {private double paneWidth = 200;private double paneHeight = 90;@Override // Override the start method in the Application class public void start(Stage primaryStage) {Pane pane = new Pane();Circle circleRed = new Circle(paneWidth / 2, 20, 10);Circle circleYellow = new Circle(paneWidth / 2, 50, 10);Circle circleGreen = new Circle(paneWidth / 2, 80, 10);circleRed.setStroke(Color.BLACK);circleYellow.setStroke(Color.BLACK);circleGreen.setStroke(Color.BLACK);circleRed.setFill(Color.WHITE);circleYellow.setFill(Color.WHITE);circleGreen.setFill(Color.WHITE);Rectangle rectangle = new Rectangle(paneWidth / 2 - 15, 5, 30, 90); rectangle.setFill(Color.WHITE);rectangle.setStroke(Color.BLACK);pane.getChildren().addAll(rectangle, circleRed, circleYellow, circleGreen);RadioButton rbRed = new RadioButton("Red");RadioButton rbYellow = new RadioButton("Yellow");RadioButton rbGreen = new RadioButton("Green");ToggleGroup group = new ToggleGroup();rbRed.setToggleGroup(group);rbYellow.setToggleGroup(group);rbGreen.setToggleGroup(group);HBox hBox = new HBox(5);hBox.getChildren().addAll(rbRed, rbYellow, rbGreen);hBox.setAlignment(Pos.CENTER);BorderPane borderPane = new BorderPane();borderPane.setCenter(pane);borderPane.setBottom(hBox);// Create a scene and place it in the stageScene scene = new Scene(borderPane, paneWidth, paneHeight + 40);primaryStage.setTitle("Exercise16_03"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagerbRed.setOnAction(e -> {circleRed.setFill(Color.RED);circleYellow.setFill(Color.WHITE);circleGreen.setFill(Color.WHITE);});rbYellow.setOnAction(e -> {circleYellow.setFill(Color.YELLOW);circleRed.setFill(Color.WHITE);circleGreen.setFill(Color.WHITE);});rbGreen.setOnAction(e -> {circleGreen.setFill(Color.GREEN);circleYellow.setFill(Color.WHITE);circleRed.setFill(Color.WHITE);});}/*** 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);}}16.3附加import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import yout.*;import javafx.scene.paint.Color;import javafx.scene.control.*;import javafx.scene.shape.Rectangle;import javafx.stage.Stage;public class Exercise16_03Extra extends Application {@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {HBox hBox = new HBox(5);TextField tfRed = new TextField();tfRed.setPrefColumnCount(4);TextField tfBlue = new TextField();tfBlue.setPrefColumnCount(4);TextField tfGreen = new TextField();tfGreen.setPrefColumnCount(4);hBox.getChildren().addAll(new Label("Red"), tfRed, new Label("Blue"), tfBlue, new Label("Green"), tfGreen);hBox.setAlignment(Pos.CENTER);BorderPane pane = new BorderPane();MandelbrotCanvas canvas = new MandelbrotCanvas();pane.setCenter(canvas);pane.setBottom(hBox);// Create a scene and place it in the stageScene scene = new Scene(pane, 425, 450);primaryStage.setTitle("Exercise16_03"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagetfRed.setOnAction(e -> {canvas.setRed(Integer.parseInt(tfRed.getText()));canvas.paint();});tfBlue.setOnAction(e -> {canvas.setBlue(Integer.parseInt(tfBlue.getText()));canvas.paint();});tfGreen.setOnAction(e -> {canvas.setGreen(Integer.parseInt(tfGreen.getText()));canvas.paint();});}/*** 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 MandelbrotCanvas extends Pane {final static int COUNT_LIMIT = 60;MandelbrotCanvas() {paint();}private void paint() {this.getChildren().clear();for (double x = -2.0; x < 2.0; x += 0.01)for (double y = -2.0; y < 2.0; y += 0.01) {Rectangle rectangle = new Rectangle(x * 100 + 200, y * 100 + 200, 1.0, 1.0);this.getChildren().add(rectangle); // Fill the rectangle with the specified colorint c = count(new Complex(x, y));if (c == COUNT_LIMIT)rectangle.setFill(Color.BLACK); // c is in a Mandelbrot set elserectangle.setFill(Color.rgb(c * red % 256, c * blue % 256, c * green % 256));}}int red = 77;int blue = 58;int green = 159;public void setRed(int red) {this.red = red;}public void setBlue(int blue) {this.blue = blue;}public void setGreen(int green) {this.green = green;}/** Returns the iteration count */int count(Complex c) {Complex z = new Complex(0, 0); // z0for (int i = 0; i < COUNT_LIMIT; i++) {z = z.multiply(z).add(c); // Get z1, z2, ...if (z.abs() > 2) return i; // The sequence is unbounded}return COUNT_LIMIT; // Indicates a bounded sequence}}}16.4import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import bel;import javafx.scene.control.TextField;import yout.GridPane;import javafx.stage.Stage;public class Exercise16_04 extends Application {private double paneWidth = 250;private double paneHeight = 60;@Override // Override the start method in the Application class public void start(Stage primaryStage) {TextField tfMile = new TextField();TextField tfKilometer = new TextField();tfMile.setAlignment(Pos.BOTTOM_RIGHT);tfKilometer.setAlignment(Pos.BOTTOM_RIGHT);GridPane pane = new GridPane();pane.setAlignment(Pos.CENTER);pane.add(new Label("Mile"), 0, 0);pane.add(tfMile, 1, 0);pane.add(new Label("Kilometer"), 0, 1);pane.add(tfKilometer, 1, 1);// Create a scene and place it in the stageScene scene = new Scene(pane, paneWidth, paneHeight);primaryStage.setTitle("Exercise16_04"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagetfMile.setOnAction(e -> {double mile = new Double(tfMile.getText().trim()).doubleValue();double kilometer = mile / 0.6241;tfKilometer.setText(new Double(kilometer).toString());});tfKilometer.setOnAction(e -> {double kilometer = newDouble(tfKilometer.getText().trim()).doubleValue();double mile = 0.6241 * kilometer;tfMile.setText(new Double(mile).toString());});}/*** 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);}}16.4附加import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.*;import yout.*;import javafx.stage.Stage;public class Exercise16_04Extra extends Application {private double paneWidth = 520;private double paneHeight = 240;private String singleFilerScheme ="Single Filers\nTaxable Income\t\tRate\n" +"Up to $27,050\t\t15%\n"+"$27,051 - $65,550\t27.5%\n" +"$65,551 - $136,750\t30.5%\n" +"$136,751 - $297,350\t35.5%\n" +"$297,351 or more\t39.1%";private String marriedJointlyFilerScheme ="Married Jointly Fliers\nTaxable Income\t\tRate\n" +"Up to $45,200\t\t15%\n"+"$45,201 - $109,250\t27.5%\n" +"$109,251 - $166,500\t30.5%\n" +"$166,501 - $297,350\t35.5%\n" +"$297,351 or more\t39.1%";private String marriedSeparatelyFilerScheme ="Married Separately Fliers\nTaxable Income\t\tRate\n" +"Up to $22,600\t\t15%\n"+"$22,601 - $54,655\t27.5%\n" +"$54,656 - $83,250\t30.5%\n" +"$83,251 - $148,675\t35.5%\n" +"$148,676 or more\t39.1%";private String headOfHouseFilerScheme ="Head of Household Fliers\nTaxable Income\t\tRate\n" +"Up to $36,250\t\t15%\n"+"$36,251 - $93,650\t27.5%\n" +"$93,651 - $151,650\t30.5%\n" +"$151,651 - $297,350\t35.5%\n" +"$297,351 or more\t39.1%";@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {RadioButton singleFiler = new RadioButton("Single filers");singleFiler.setSelected(true);RadioButton marriedJointly = new RadioButton("Married filing jointly or qualifying widow(er)");RadioButton marriedSeparately = new RadioButton("Married filing separately");RadioButton headOfHousehold = new RadioButton("Head of Household");ToggleGroup group = new ToggleGroup();singleFiler.setToggleGroup(group);marriedJointly.setToggleGroup(group);marriedSeparately.setToggleGroup(group);headOfHousehold.setToggleGroup(group);VBox vBox = new VBox(5);vBox.getChildren().addAll(singleFiler, marriedJointly, marriedSeparately,headOfHousehold);HBox hBox = new HBox(5);Label lblDescription = new Label(singleFilerScheme);hBox.getChildren().addAll(vBox, lblDescription);GridPane pane = new GridPane();pane.setHgap(5);pane.setVgap(5);TextField tfTaxableIncome = new TextField();TextField tfTax = new TextField();tfTaxableIncome.setPrefColumnCount(8);tfTax.setPrefColumnCount(8);tfTax.setEditable(false);pane.setAlignment(Pos.CENTER);pane.add(new Label("Taxable income"), 0, 0);pane.add(tfTaxableIncome, 1, 0);pane.add(new Label("Tax"), 0, 1);pane.add(tfTax, 1, 1);Button btComputeTax = new Button("Compute Tax");pane.add(btComputeTax, 1, 2);VBox vBoxAll = new VBox(5);vBoxAll.getChildren().addAll(new Label("Select Tax Status"), hBox, pane);// Create a scene and place it in the stageScene scene = new Scene(vBoxAll, paneWidth, paneHeight);primaryStage.setTitle("Exercise16_04"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagesingleFiler.setOnAction(e -> lblDescription.setText(singleFilerScheme)); marriedJointly.setOnAction(e ->lblDescription.setText(marriedJointlyFilerScheme));marriedSeparately.setOnAction(e ->lblDescription.setText(marriedSeparatelyFilerScheme));headOfHousehold.setOnAction(e ->lblDescription.setText(headOfHouseFilerScheme));btComputeTax.setOnAction(e -> {Tax tax = new Tax(); // Programming Exercise 10.8int status = 0;if (singleFiler.isSelected())status = 0;else if (marriedJointly.isSelected())status = 1;else if (marriedSeparately.isSelected())status = 2;else if (headOfHousehold.isSelected())status = 3;tax.setFilingStatus(status);tax.setTaxableIncome(Double.parseDouble(tfTaxableIncome.getText() + ""));tfTax.setText(tax.findTax() + "");});}/*** 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);}}16.5import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import bel;import javafx.scene.control.TextField;import yout.GridPane;import javafx.stage.Stage;public class Exercise16_05 extends Application {private double paneWidth = 250;private double paneHeight = 90;@Override // Override the start method in the Application class public void start(Stage primaryStage) {TextField tfDecimal = new TextField();TextField tfHex = new TextField();TextField tfBinary = new TextField();tfDecimal.setAlignment(Pos.BOTTOM_RIGHT);tfHex.setAlignment(Pos.BOTTOM_RIGHT);tfBinary.setAlignment(Pos.BOTTOM_RIGHT);tfHex.setAlignment(Pos.BOTTOM_RIGHT);GridPane pane = new GridPane();pane.setAlignment(Pos.CENTER);pane.setHgap(10);pane.add(new Label("Decimal"), 0, 0);pane.add(tfDecimal, 1, 0);pane.add(new Label("Hex"), 0, 1);pane.add(tfHex, 1, 1);pane.add(new Label("Binary"), 0, 2);pane.add(tfBinary, 1, 2);// Create a scene and place it in the stageScene scene = new Scene(pane, paneWidth, paneHeight);primaryStage.setTitle("Exercise16_05"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stagetfDecimal.setOnAction(e -> {int decimal = Integer.parseInt(tfDecimal.getText());tfHex.setText(Integer.toHexString(decimal));tfBinary.setText(Integer.toBinaryString(decimal));});tfHex.setOnAction(e -> {int decimal = Integer.parseInt(tfHex.getText(), 16);tfDecimal.setText(decimal + "");tfBinary.setText(Integer.toBinaryString(decimal));});tfBinary.setOnAction(e -> {int decimal = Integer.parseInt(tfBinary.getText(), 2);tfDecimal.setText(decimal + "");tfHex.setText(Integer.toHexString(decimal));});}/*** 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);}}16.5附加import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.*;import yout.*;import javafx.stage.Stage;public class Exercise16_05Extra extends Application {private double paneWidth = 240;private double paneHeight = 200;private Button bt1 = new Button("1");private Button bt2 = new Button("2");private Button bt3 = new Button("3");private Button bt4 = new Button("4");private Button bt5 = new Button("5");private Button bt6 = new Button("6");private Button bt7 = new Button("7");private Button bt8 = new Button("8");private Button bt9 = new Button("9");private Button bt0 = new Button("0");private Button btAdd = new Button("+");private Button btSubtract = new Button("-");private Button btMultiply = new Button("*");private Button btDivide = new Button("/");private Button btRemainder = new Button("%");private Button btSqrt = new Button("sqrt");private Button btDecimal = new Button(".");private Button btEqual = new Button("=");private TextField tf = new TextField();@Override // Override the start method in the Application class public void start(Stage primaryStage) {GridPane pane = new GridPane();pane.setHgap(5);pane.setVgap(5);pane.add(new Button("MC"), 0, 0);pane.add(bt7, 1, 0);pane.add(bt8, 2, 0);pane.add(bt9, 3, 0);pane.add(btDivide, 4, 0);pane.add(btSqrt, 5, 0);pane.add(new Button("MR"), 0, 1);pane.add(bt4, 1, 1);pane.add(bt5, 2, 1);pane.add(bt6, 3, 1);pane.add(btMultiply, 4, 1);pane.add(btRemainder, 5, 1);pane.add(new Button("MS"), 0, 2);pane.add(bt1, 1, 2);pane.add(bt2, 2, 2);pane.add(bt3, 3, 2);pane.add(btSubtract, 4, 2);pane.add(new Button("1/x"), 5, 2);pane.add(new Button("M+"), 0, 3);pane.add(bt0, 1, 3);pane.add(new Button("+/-"), 2, 3);pane.add(btDecimal, 3, 3);pane.add(btAdd, 4, 3);pane.add(btEqual, 5, 3);HBox hBox = new HBox(5);hBox.getChildren().addAll(new Button("Back"), new Button("CE"), new Button("C"));hBox.setAlignment(Pos.BASELINE_RIGHT);VBox vBox = new VBox(5);vBox.getChildren().addAll(tf, hBox, pane);// Create a scene and place it in the stageScene scene = new Scene(vBox, paneWidth, paneHeight);primaryStage.setTitle("Exercise16_05"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stageprimaryStage.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);}}16.6import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import bel;import javafx.scene.control.RadioButton;import javafx.scene.control.TextField;。
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版 梁勇 著) 第二章 基本程序设计 练习题答案
本人在自学编程过程中,发现本书答案很难找,找到的要么不完整、要么错误百出,所以我将自己所做的 练习题答案,提供给有需要者,供大家交流。本章答案均为本人一字一字所敲,答案均经过验证,虽为初学者, 但代码均按照书中规范要求书写,如有错误或更好的建议,请指正交流。
// 第二章 P59 练习题2.1 (将摄氏温度转为华氏温度) import java.util.Scanner;
public class CelsiusToFahrenheit {
public static void main(String[] args) { // 华氏温度和摄氏温度的转换公式为:华氏温度 = (9/5)*摄氏温度+32 Scanner input = new Scanner(System.in);
System.out.print("Enter the time zone offset to GMT: "); long timeZoneOffset = input.nextLong(); // 此处用long还是int?
long totalMilliseconds = System.currentTimeMillis(); long totalSeconds = totalMilliseconds / 1000; long currentSecond = totalSeconds % 60; long totalMinutes = totalSeconds / 60; long currentMinute = totalMinutes % 60; long totalHours = totalMinutes / 60; long currentHour = totalHours % 24; long hour = currentHour + timeZoneOffset;
《Java语言程序设计(基础篇)》(第10版 梁勇 著)第二十一章练习题答案
《Java语言程序设计(基础篇)》(第10版梁勇著)第二十一章练习题答案21.1import java.util.*;public class Exercise21_01 {public static void main(String[] args) {LinkedHashSet<String> set1 = new LinkedHashSet<String>(Arrays.asList( new String[]{"George", "Jim", "John", "Blake", "Kevin", "Michael"}));LinkedHashSet<String> set1Clone1 = (LinkedHashSet<String>)set1.clone(); LinkedHashSet<String> set1Clone2 = (LinkedHashSet<String>)set1.clone();LinkedHashSet<String> set2 = new LinkedHashSet<String>(Arrays.asList( new String[] {"George", "Katie", "Kevin", "Michelle", "Ryan"}));set1.addAll(set2);set1Clone1.removeAll(set2);set1Clone2.retainAll(set2);System.out.println("The union of the two sets is " + set1);System.out.println("The difference of the two sets is " + set1Clone1); System.out.println("The intersection of the two sets is " + set1Clone2); }}21.1附加import java.util.*;public class Exercise21_01Extra {public static void main(String[] args) {System.out.print("Enter a string: ");Scanner input = new Scanner(System.in);String s = input.nextLine();Character[] list1 = {'A', 'E', 'I', 'O', 'U'};Set<Character> vowels = new HashSet<>(Arrays.asList(list1));Set<Character> vowelsInString = new HashSet<>();Set<Character> consonantsInString = new HashSet<>();int numbeOfVowels = 0;int numbeOfConsonants = 0;for (int i = 0; i < s.length(); i++) {char ch = Character.toUpperCase(s.charAt(i));if (Character.isLetter(ch)) {if (vowels.contains(ch)) {if (!vowelsInString.contains(ch)) {vowelsInString.add(ch);numbeOfVowels++;}}else if (!consonantsInString.contains(ch)) {consonantsInString.add(ch);numbeOfConsonants++;}}}System.out.println("The number of vowels is " + numbeOfVowels);System.out.println("The number of consonants is " + numbeOfConsonants); }}21.2import java.util.*;import java.io.*;public class Exercise21_02 {public static void main(String[] args) {if (args.length != 1) {System.out.println("Usage: java Exercise21_02 fullfilename");System.exit(1);}String filename = args[0];// Create a tree set to hold the wordsTreeSet<String> treeSet = new TreeSet<String>();try {Scanner in = new Scanner(new File(filename));String line;while ((line = in.nextLine()) != null) {String[] tokens = line.split("[ |\n|\t|\r|.|,|)|(|-|\"]");for (int i = 0; i < tokens.length; i++)treeSet.add(tokens[i]);}}catch (Exception ex) {System.err.println(ex);}// Get an iterator for the setIterator iterator = treeSet.iterator();// Display mappingsSystem.out.println("\nDisplay words in ascending order ");while (iterator.hasNext()) {System.out.println(iterator.next());}}}21.3import java.util.*;import java.io.*;public class Exercise21_03 {public static void main(String[] args) {// Check usageif (args.length != 1) {System.out.println("Usage: java Exercise21_03 file.java");System.exit(1);}// Array of all Java keywords + true + nullString[] keywordString = {"abstract", "finally", "public", "boolean", "float", "return", "break", "for", "short", "byte","goto", "static", "case", "if", "super", "catch", "implements", "switch", "char", "import", "synchronized", "class","instanceof", "this", "const", "int", "throw", "continue","interface", "throws", "default", "long", "transient", "do","native", "try", "double", "new", "void", "else", "package","volatile", "extends", "private", "while", "final","protected", "true", "null"};Set<String> keywordSet =new HashSet<String>(Arrays.asList(keywordString));int count = 0;try {Scanner input = new Scanner(new File(args[0]));String text = "";while (input.hasNext()) {String line = input.nextLine();line = stripLineComments(line);line = stripLineStringLiterals(line);text += line + " ";}text = stripParagraghComments(text);String[] tokens = text.split("[ \\[,()\\]]");for (String token: tokens) {if (keywordSet.contains(token))count++;}System.out.println("The number of keywords in the program is " + count);}catch (Exception ex) {ex.printStackTrace();}}/* Strip line comments */private static String stripLineComments(String line) {int index = line.indexOf("//");if (index < 0)return line;elsereturn line.substring(0, index);}/* Strip string literals */private static String stripLineStringLiterals(String line) {int start = line.indexOf("\"");int end = line.indexOf("\"", start + 1);while (start > 0 && end > 0) {line = line.substring(0, start) + line.substring(end + 1);start = line.indexOf("\"");end = line.indexOf("\"");}return line;}/* Strip paragraph comments */private static String stripParagraghComments(String text) {int start = text.indexOf("/*");int end = text.indexOf("*/");while (start > 0 && end > 0) {text = text.substring(0, start) + text.substring(end + 2);start = text.indexOf("/*");end = text.indexOf("*/");}return text;}}/** This is an incorrect version. It does not count the case such as (this. Here the this keyword* is not counted. It does not exclude keywords in the comments*import java.util.*;import java.io.*;public class Exercise20_03 {public static void main(String[] args) {// Check usageif (args.length != 1) {System.out.println("Usage: java Exercise20_03 file.java");System.exit(0);}// Array of all Java keywords + true + nullString[] keywordString = {"abstract", "finally", "public","boolean", "float", "return", "break", "for", "short", "byte", "goto", "static", "case", "if", "super", "catch", "implements", "switch", "char", "import", "synchronized", "class","instanceof", "this", "const", "int", "throw", "continue","interface", "throws", "default", "long", "transient", "do","native", "try", "double", "new", "void", "else", "package","volatile", "extends", "private", "while", "final","protected", "true", "null"};Set<String> keywordSet =new HashSet<String>(Arrays.asList(keywordString));int count = 0;try {Scanner input = new Scanner(new File(args[0]));while (input.hasNext()) {String token = input.next();if (keywordSet.contains(token))count++;}System.out.println("The number of keywords in the program is " + count);}catch (Exception ex) {ex.printStackTrace();}}}*/21.4import java.util.Scanner;import java.util.HashSet;import java.util.Arrays;public class Exercise21_04 {public static void main(String[] args) throws Exception {HashSet<Character> set1 = new HashSet<Character>(Arrays.asList( new Character[]{'A', 'E', 'I', 'O', 'U'}));System.out.print("Enter a filename: ");Scanner input = new Scanner(System.in);String filename = input.nextLine();input = new Scanner(new java.io.File(filename));int countVowels = 0;int countConsonants = 0;while (input.hasNext()) {String s = input.nextLine().toUpperCase();for (int i = 0; i < s.length(); i++) {if (set1.contains(s.charAt(i)))countVowels++;else if (Character.isLetter(s.charAt(i)))countConsonants++;}}System.out.println("The number of vowels is " + countVowels + " and consonanats is " +countConsonants);}}21.5/*** Usage: Copy this class to the folder, run it with java JavaToHTMLftim * to generate* HTM file for all the .java file in this folder. The generated .htm files are* stored in the same folder*/import java.util.*;import java.io.*;public class Exercise21_05 {// Array of all Java keywords + true + false + nullstatic String[] keywordString = {"abstract", "assert", "boolean","break", "byte", "case", "catch", "char", "class", "const","continue", "default", "do", "double", "else", "enum","extends", "for", "final", "finally", "float", "goto", "if","implements", "import", "instanceof", "int", "interface","long", "native", "new", "package", "private", "protected","public", "return", "short", "static", "strictfp", "super","switch", "synchronized", "this", "throw", "throws","transient", "try", "void", "volatile", "while","true", "false", "null"};static Set<String> keywordSet =new HashSet<String>(Arrays.asList(keywordString));/** Main method */public static void main(String[] args) throws Exception {// Check usageif (args.length != 2) {System.out.println("Usage: java Exercise20_10 javaSourcefile htmlfile");System.exit(1);}Scanner input = new Scanner(new File(args[0]));PrintWriter output = new PrintWriter(new File(args[1]));JavaToHTML(input, output);}static boolean stringToken = false;static String inputFileName;public static void JavaToHTML(Scanner input, PrintWriter output) { try {output.format("%s\r\n", "<html>");output.format("%s\r\n", "<head>");output.format("%s\r\n","<title>Intro to Java Programming, 6E - " + inputFileName +"</title>");output.format("%s\r\n","<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">");output.format("%s\r\n", "<style type = \"text/css\">");output.format("%s\r\n","body {font-family: \"Courier New\", sans-serif; font-size: 100%; color: black}");output.format("%s\r\n",".keyword {color: #000080; font-weight: bold}");output.format("%s\r\n", ".comment {color: #008000}");output.format("%s\r\n", ".literal {color: #0000ff}");// Match the color in the text// output.format("%s\r\n", ".keyword {color: black; font-weight: bold}");// output.format("%s\r\n", ".comment {color: #77797C}");// output.format("%s\r\n", ".literal {color: #007346; font-weight: bold}");output.format("%s\r\n", "</style>");output.format("%s\r\n", "</head>");output.format("%s\r\n", "<body>");output.format("%s\r\n", "<pre>");String text = "";String temp;// Read all lineswhile (input.hasNext()) {temp = input.nextLine();text += temp + "\r\n";}text = text.replaceAll(">", ">");text = text.replaceAll("<", "<");translateToHTML(text, input, output);output.format("%s\r\n", "</pre>");output.format("%s\r\n", "</body>");output.format("%s\r\n", "</html>");}catch (Exception ex) {System.out.println(ex);}finally {try {input.close();output.close();}catch (Exception ex) {}}}/** Translate Java source code to HTML */static void translateToHTML(String text, Scanner input, PrintWriter output) throws Exception {text = text.replaceAll("// ", "LINECOMMENT");text = text.replaceAll("/\\*", "BLOCKCOMMENT");String token;while (text != null && text.length() > 0) {// * and / are in conflict with /* and //String[] parts = text.split("[%\\+\\-\\*/\r\n\t \\[\\].;(){},]", 2); token = parts[0];if (token.length() > 1 && token.startsWith("LINECOMMENT")) {output.format("%s", "<span class = \"comment\">");parts = text.split("\r\n", 2);text = parts[1];output.format("%s", parts[0].replaceAll("LINECOMMENT", "// "));output.format("%s", "</span>\r\n");continue;}else if (token.length() > 1 && token.startsWith("BLOCKCOMMENT")) {output.format("%s", "<span class = \"comment\">");parts = text.split("\\*/", 2);text = parts[1];output.format("%s", parts[0].replaceAll("BLOCKCOMMENT", "/*") +"*/");output.format("%s", "</span>");continue;}else if (token.length() > 1 && token.matches("'\\w'*")) {output.format("%s", "<span class = \"literal\">");output.format("%s", token);output.format("%s", "</span>");}else if (token.startsWith("\"") && token.endsWith("\"") &&(token.length() > 1)) {output.format("%s", "<span class = \"literal\">" + token+ "</span>");}else if (token.startsWith("'") && token.endsWith("'") &&(token.length() > 1)) {output.format("%s", "<span class = \"literal\">" + token+ "</span>");}else if (token.equals("' '")) {output.format("%s", "<span class = \"literal\">" + token+ "</span>");}else if (token.startsWith("\"") && token.endsWith("\"") &&(token.length() == 1)) {if (stringToken) {output.format("%s", token + "</span>");stringToken = false;}else {output.format("%s", "<span class = \"literal\">" + token); stringToken = true;}}else if (token.startsWith("\"")) {output.format("%s", "<span class = \"literal\">" + token); stringToken = true;}else if (token.endsWith("\"") && (!token.endsWith("\\\""))) { output.format("%s", token);output.format("%s", "</span>");stringToken = false;}else if (token.matches("\\d+")) { // Check if numericoutput.format("%s", "<span class = \"literal\">" + token +"</span>");}else if (!stringToken && keywordSet.contains(token)) {output.format("%s", "<span class = \"keyword\">" + token +"</span>");}else {output.format("%s", token);}if (token.length() < text.length()) {if (text.charAt(token.length()) == '<')output.format("%s", "<");else if (text.charAt(token.length()) == '>')output.format("%s", ">");elseoutput.format("%s", text.charAt(token.length()));}if (parts.length == 2) {text = parts[1];}}}}21.6import java.util.*;public class Exercise21_06 {public static void main(String[] args) {// Create a tree map to hold words and key and count as value TreeMap<Integer, Integer> treeMap = new TreeMap<>();Scanner input = new Scanner(System.in);while (true) {// Enter an integerSystem.out.print("Enter an integer: ");int number = input.nextInt();if (number == 0) break;Integer key = new Integer(number);if (treeMap.get(key) != null) {int value = ((Integer)treeMap.get(key)).intValue();value++;treeMap.put(key, new Integer(value));}else {treeMap.put(key, new Integer(1));}}Integer max = Collections.max(treeMap.values());Set<Integer> keys = treeMap.keySet();Iterator<Integer> iterator = keys.iterator();while (iterator.hasNext()) {Object key = iterator.next();Integer value = (Integer)(treeMap.get(key));if (value.equals(max)) {System.out.println("Number " + key + " occurred most");}}}}21.7import java.util.*;public class Exercise21_07 {public static void main(String[] args) {// Text in a stringString text = "Have a good day. Have a good class. " + "Have a good visit. Have fun!";// Create a hash map to hold words and key and count as value HashMap<String, Integer> hashMap = new HashMap<>();String[] tokens = text.split("[ |.|!|?]");for (String key: tokens) {if (hashMap.get(key) != null) {hashMap.put(key, hashMap.get(key).intValue() + 1);}else {if (key.trim().length() > 0)hashMap.put(key, 1);}}// Get an entry set for the tree mapSet<Map.Entry<String, Integer>> entrySet = hashMap.entrySet();ArrayList<WordOccurrence> list = new ArrayList<>();for (Map.Entry<String, Integer> entry: entrySet) {list.add(new WordOccurrence(entry.getKey(), entry.getValue())); }Collections.sort(list);for (WordOccurrence item: list) {System.out.println(item);}}}class WordOccurrence implements Comparable<WordOccurrence> {String word;int count;public WordOccurrence(String word, int count) {this.word = word;this.count = count;}@Overridepublic int compareTo(WordOccurrence o) {return count - o.count;}@Overridepublic boolean equals(Object o) {return word.equals(((WordOccurrence)o).word);}@Overridepublic String toString() {return word + ": " + count;}}21.8import java.util.*;import java.io.*;public class Exercise21_08 {public static void main(String[] args) {if (args.length != 1) {System.out.println("Usage: java Exercise21_08 fullfilename");System.exit(1);}String filename = args[0];// Create a tree map to hold words as key and count as valueTreeMap<String, Integer> treeMap = new TreeMap<String, Integer>();try {Scanner input = new Scanner(new File(filename));while (input.hasNext()) {String line = input.nextLine();String[] words = line.split("[ @!~{}\\[\\]$#^&*\n\t\r.,;?'\")(]");for (int i = 0; i < words.length; i++) {if (words[i].trim().length() > 0 &&words[i].trim().matches("[A-Z|a-z]+")) {String key = words[i].toLowerCase();if (treeMap.get(key) != null) {int count = treeMap.get(key);count++;treeMap.put(key, count);}else {treeMap.put(key, 1);}}}}}catch (Exception ex) {ex.printStackTrace();}// Get an entry set for the tree mapSet<Map.Entry<String, Integer>> entrySet = treeMap.entrySet();// Display words in alphabetical orderSystem.out.println("\nDisplay words and their count in " + " ascending order of the words");for (Map.Entry<String, Integer> entry: entrySet)System.out.println(entry.getValue() + "\t" + entry.getKey()); }}21.9import java.util.*;public class Exercise21_09 {public static void main(String[] args) {String[][] stateCapital = {{"Alabama", "Montgomery"},{"Alaska", "Juneau"},{"Arizona", "Phoenix"},{"Arkansas", "Little Rock"},{"California", "Sacramento"},{"Colorado", "Denver"},{"Connecticut", "Hartford"},{"Delaware", "Dover"},{"Florida", "Tallahassee"},{"Georgia", "Atlanta"},{"Hawaii", "Honolulu"},{"Idaho", "Boise"},{"Illinois", "Springfield"},{"Indiana", "Indianapolis"},{"Iowa", "Des Moines"},{"Kansas", "Topeka"},{"Kentucky", "Frankfort"},{"Louisiana", "Baton Rouge"},{"Maine", "Augusta"},{"Maryland", "Annapolis"},{"Massachusettes", "Boston"},{"Michigan", "Lansing"},{"Minnesota", "Saint Paul"},{"Mississippi", "Jackson"},{"Missouri", "Jefferson City"},{"Montana", "Helena"},{"Nebraska", "Lincoln"},{"Nevada", "Carson City"},{"New Hampshire", "Concord"},{"New Jersey", "Trenton"},{"New York", "Albany"},{"New Mexico", "Santa Fe"},{"North Carolina", "Raleigh"},{"North Dakota", "Bismark"},{"Ohio", "Columbus"},{"Oklahoma", "Oklahoma City"},{"Oregon", "Salem"},{"Pennslyvania", "Harrisburg"},{"Rhode Island", "Providence"},{"South Carolina", "Columbia"},{"South Dakota", "Pierre"},{"Tennessee", "Nashville"},{"Texas", "Austin"},{"Utah", "Salt Lake City"},{"Vermont", "Montpelier"},{"Virginia", "Richmond"},{"Washington", "Olympia"},{"West Virginia", "Charleston"},{"Wisconsin", "Madison"},{"Wyoming", "Cheyenne"}};Map<String, String> map = new HashMap<String, String>();for (int i = 0; i < stateCapital.length; i++)map.put(stateCapital[i][0].toLowerCase(), stateCapital[i][1]);Scanner input = new Scanner(System.in);System.out.print("Enter a state: ");String state = input.nextLine().toLowerCase().trim();if (map.containsKey(state))System.out.println("The capital is " +map.get(state));elseSystem.out.println("No such state ");}}21.10import java.util.*;import java.io.*;public class Exercise21_10 {public static void main(String[] args) {// Prompt the user to enter a Java source fileScanner input = new Scanner(System.in);System.out.print("Enter a file name: ");String filename = input.nextLine();// Array of all Java keywords + true + nullString[] keywordString = { "abstract", "finally", "public", "boolean", "float", "return", "break", "for", "short", "byte", "goto", "static","case", "if", "super", "catch", "implements", "switch", "char","import", "synchronized", "class", "instanceof", "this", "const","int", "throw", "continue", "interface", "throws", "default", "long","transient", "do", "native", "try", "double", "new", "void", "else","package", "volatile", "extends", "private", "while", "final","protected", "true", "null" };Set<String> keywordSet = newHashSet<String>(Arrays.asList(keywordString));int count = 0;try {input = new Scanner(new File(filename));String text = "";while (input.hasNext()) {String line = input.nextLine();line = stripLineComments(line);line = stripLineStringLiterals(line);text += line + " ";}text = stripParagraghComments(text);TreeMap<String, Integer> map = new TreeMap<String, Integer>();String[] tokens = text.split("[ \\[,()\\]]");for (String token : tokens) {if (keywordSet.contains(token))if (map.get(token) == null) {map.put(token, 1);} else {int value = map.get(token);value++;map.put(token, value);}}// Get all entries into a setSet<Map.Entry<String, Integer>> entrySet = map.entrySet();// Get key and value from each entryfor (Map.Entry<String, Integer> entry: entrySet)System.out.println(entry.getValue() + "\t" + entry.getKey()); } catch (Exception ex) {ex.printStackTrace();}}/* Strip line comments */private static String stripLineComments(String line) {int index = line.indexOf("//");if (index < 0)return line;elsereturn line.substring(0, index);}/* Strip string literals */private static String stripLineStringLiterals(String line) {int start = line.indexOf("\"");int end = line.indexOf("\"", start + 1);while (start > 0 && end > 0) {line = line.substring(0, start) + line.substring(end + 1);start = line.indexOf("\"");end = line.indexOf("\"");}return line;}/* Strip paragraph comments */private static String stripParagraghComments(String text) {int start = text.indexOf("/*");int end = text.indexOf("*/");while (start > 0 && end > 0) {text = text.substring(0, start) + text.substring(end + 2);start = text.indexOf("/*");。
[修订]java语言程序设计基础篇第八章第十题编程参考答案
[修订]java语言程序设计基础篇第八章第十题编程参考答案为二次方程式ax2+bx+c=0设计一个名为QuadraticEquation的类。
这个类包括: 代表三个系数的私有数据域a、b、c。
一个参数为a、b、c的构造方法。
a、b、c的三个get方法。
一个名为getDiscriminant()的方法返回判别式,b2-4ac。
一个名为getRoot1()和getRoot2()的方法返回等式的两个根。
这些方法只有在判别式为非负数时才有用。
如果判别式为负,方法返回0。
画出该类的UML图。
实现这个类。
编写一个测试程序,提示用户输入a、b、c的值,然后显示判别式的结果。
如果判别式为正数,显示两个根;如果判别式为0,显示一个根;否则,显示“The equation has no roots”。
代码:class QuadraticEquation{private int a,b,c;QuadraticEquation(){}public QuadraticEquation(int a,int b,int c){this.a=a;this.b=b;this.c=c;}public int getA(){return a;}public int getB(){return b;}public int getC(){return c;}public int getDiscriminant(){if(b*b-4*a*c>=0)return b*b-4*a*c;elsereturn 0;}public int getRoot1(){if(b*b-4*a*c>=0)return (int)((-b+Math.pow(b*b-4*a*c, 0.5))/(2*a)); elsereturn 0;}public int getRoot2(){if(b*b-4*a*c>=0)return (int)((-b-Math.pow(b*b-4*a*c, 0.5))/(2*a)); elsereturn 0;}}public class XiTi810 {public static void main(String[] args){System.out.println("请输入要计算的方程的系数a、b和c:");java.util.Scanner input =new java.util.Scanner(System.in);System.out.print("a=");int a=input.nextInt();System.out.print("b=");int b=input.nextInt();System.out.print("c=");int c=input.nextInt();QuadraticEquation q=new QuadraticEquation(a,b,c);q.getDiscriminant();if(q.getDiscriminant()>0)System.out.println("它们的根为:"+q.getRoot1()+"和"+q.getRoot2());else if(q.getDiscriminant()==0)System.out.println("此方程只有一个根为:"+q.getRoot1());elseSystem.out.println("方程无解");}}。
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语言程序设计基础篇的知识。
1. 什么是Java语言的特点?
答:Java语言具有简单、面向对象、分布式、多线程、动态、解释性等特点。
2. Java语言有哪些基本数据类型?
答:Java语言的基本数据类型包括整型、浮点型、字符型、布尔型等。
3. 什么是Java语言中的变量?
答:变量是用来存储数据的内存空间,它具有数据类型和名称。
4. Java语言中的运算符有哪些?
答:Java语言中的运算符包括算术运算符、关系运算符、逻辑运算符、位运算符等。
5. 什么是Java语言中的控制语句?
答:控制语句用于控制程序的执行流程,包括顺序结构、选择结构、循环结构等。
6. 什么是Java语言中的数组?
答:数组是一种用来存储多个相同类型数据的数据结构。
7. Java语言中的方法是什么?
答:方法是一段用来完成特定任务的代码,它可以被重复使用。
8. 什么是Java语言中的类和对象?
答:类是一种模板,用来描述对象的属性和行为;对象是类的实例,具有特定的属性和行为。
通过复习这些问题的答案,我们可以更好地理解和掌握Java语言程序设计基础篇的知识,为以后的学习和实践打下坚实的基础。
希望大家在学习Java语言程序设计基础篇的过程中能够不断努力,取得更好的成绩。
《Java语言程序设计-基础篇》答案-第09章
第9章 抽象类与接口复习题9.1 答:(c)和(f)定义了合法抽象类。
9.2 答:约束其子类必须实现这2个方法。
9.3 答:(d)是正确的。
9.4 答:不正确,原因是类型转换错误。
9.5 答:使用接口提供了一般程序设计(generic programming)的形式。
允许参数接收范围更广的类型。
同时由于Java 不支持类的多继承,使用接口可以使类继承一个父类的同时实现多个接口。
9.6 答:(1)如果没有覆盖clone 方法,则编译出错,找不到clone 方法。
(2)如果没有实现Cloneable 接口,则House 类的对象不能clone,执行如下语句时,h2得到的是null。
House h1 = new House(); House h2 = (House)(h1.clone());9.7 答:输出结果: false true9.8 答:错误为:GeometricObject y = x.clone();clone()方法的返回值是Object 类,赋值给y 时需要强制类型转换。
9.9 答:Object[] objs = new int[10]; 不可以 Object[] objs = new String[100]; 可以 Object[] objs = new Object[50]; 可以 Object[] objs = new Calendar[10]; 可以9.10答:略9.11答:Integer i = new Integer("23"); //正确Integer i = new Integer(23); //正确 Integer i = Integer.valueOf("23");//正确 Integer i = Integer.parseInt("23", 8);//正确 Double d = new Double();//错误课后答案网ww w.kh da w .c omDouble d = Double.valueOf("23.45"); //正确int i = (Integer.valueOf("23")).intValue(); //正确double d = (Double.valueOf("23.4")).doubleValue(); //正确 int i = (Double.valueOf("23.4")).intValue(); //正确 String s = (Double.valueOf("23.4")).toString(); //正确9.12 答:可以使用parseXXX 方法和toString 方法9.13 答:向下类型转换时,没有保证类型的一致。
《Java语言程序设计(基础篇)》(第10版梁勇著)第三章练习题答案
《Java语言程序设计(基础篇)》(第10版梁勇著)第三章练习题答案《Java语言程序设计(基础篇)》(第10版梁勇著)第三章练习题答案3.1public class Exercise03_01 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a, b, c: ");double a = input.nextDouble();double b = input.nextDouble();double c = input.nextDouble();double discriminant = b * b - 4 * a * c;if (discriminant < 0) {System.out.println("The equation has no real roots");}else if (discriminant == 0) {double r1 = -b / (2 * a);System.out.println("The equation has one root " + r1);}else { // (discriminant > 0)double r1 = (-b + Math.pow(discriminant, 0.5)) / (2 * a);double r2 = (-b - Math.pow(discriminant, 0.5)) / (2 * a);System.out.println("The equation has two roots " + r1 + " and " + r2);}}}3.1附加public class Exercise03_01Extra {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter a numerator: ");int numerator = input.nextInt();System.out.print("Enter a denominator: ");int denominator = input.nextInt();if (numerator < denominator) {System.out.println(numerator + " / " + denominator + " is a proper fraction");}else if (numerator % denominator == 0) {System.out.print(numerator + " / " + denominator + " is an improper fraction ");System.out.println("and it can be reduced to " + numerator / denominator);}else {System.out.print(numerator + " / " + denominator + " is an improper fraction ");System.out.println("and its mixed fraction is " + numerator / denominator + " + " +numerator % denominator + " / " + denominator);}}}3.2public class Exercise03_02 {public static void main(String[] args) {Scanner input = new Scanner(System.in);int number1 = (int)(System.currentTimeMillis() % 10);int number2 = (int)(System.currentTimeMillis() * 7 % 10);int number3 = (int)(System.currentTimeMillis() * 3 % 10);System.out.print("What is " + number1 + " + " + number2 + " + " +number3 + "? ");int answer = input.nextInt();System.out.println(number1 + " + " + number2 + " + " + number3 +" = " + answer + " is " +(number1 + number2 + number3 == answer));}}3.2附加public class Exercise03_02Extra {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter the coordinates for two points: ");double x1 = input.nextDouble();double y1 = input.nextDouble();double x2 = input.nextDouble();double y2 = input.nextDouble();double m = (y2 - y1) / (x2 - x1);double b = y1 - m * x1;System.out.print("The line equation for two points (" + x1 + ", " + y1 + ") and (" + x2 + ", " + y2 + ") is " + "y = ");if (m == -1)System.out.print("-x");else if (m == 1)System.out.print("x");elseSystem.out.print(m + "x");if (b > 0)System.out.println(" + " + b);else if (b < 0)System.out.println(" - " + (-1 * b));else// b is 0System.out.println();}}3.3public class Exercise03_03 {public static void main(String[] args) {Scanner input = new Scanner(System.in); System.out.print("Enter a, b, c, d, e, f: ");double a = input.nextDouble();double b = input.nextDouble();double c = input.nextDouble();double d = input.nextDouble();double e = input.nextDouble();double f = input.nextDouble();double detA = a * d - b * c;if (detA == 0) {System.out.println("The equation has no solution"); }else {double x = (e * d - b * f) / detA;double y = (a * f- e * c) / detA;System.out.println("x is " + x + " and y is " + y);}}}3.3附加public class Exercise03_03Extra {public static void main(String[] args) {final double RADIUS = 5;double angle = Math.random() * 2 * Math.PI;double x = RADIUS * Math.random() * Math.cos(angle);double y = RADIUS * Math.sin(angle);double distance = Math.pow(x * x + y * y, 0.5);System.out.println("The point is (" + x + ", " + y + ") and its distance to the center is " + distance);}}3.4public class Exercise03_04 {public static void main(String[] args) {int number = (int)(Math.random() * 12) + 1;// or int number = (int)(System.currentTimeMillis() % 12 + 1);// or int number = (int)(Math.random() * 12) + 1;if (number == 1)System.out.println("Month is Januaray");else if (number == 2)System.out.println("Month is Feburary");else if (number == 3)System.out.println("Month is March");else if (number == 4)System.out.println("Month is April");else if (number == 5)System.out.println("Month is May");else if (number == 6)System.out.println("Month is June");else if (number == 7)System.out.println("Month is July");else if (number == 8)System.out.println("Month is August");else if (number == 9)System.out.println("Month is September");else if (number == 10)System.out.println("Month is October");else if (number == 11)System.out.println("Month is November");else// if (number == 12)System.out.println("Month is December");}}3.5public class Exercise03_05 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter an integer for todaySystem.out.print("Enter today抯 day: ");int today = input.nextInt();System.out.print("Enter the number of days elapsed since today: ");int elapsedDays = input.nextInt();String nameForToday;if (today == 0)nameForToday = "Sunday";else if (today == 1)nameForToday = "Monday";else if (today == 2)nameForToday = "Tuesday";else if (today == 3)nameForToday = "Wednesday";else if (today == 4)nameForToday = "Thursday";else if (today == 5)nameForToday = "Friday";else// if (today == 6)nameForToday = "Saturday";int futureDay = (today + elapsedDays) % 7; String nameForFutureDay;if (futureDay == 0)nameForFutureDay = "Sunday";else if (futureDay == 1) nameForFutureDay = "Monday";else if (futureDay == 2) nameForFutureDay = "Tuesday";else if (futureDay == 3) nameForFutureDay = "Wednesday";else if (futureDay == 4) nameForFutureDay = "Thursday";else if (futureDay == 5) nameForFutureDay = "Friday";else// if (futureDay == 6) nameForFutureDay = "Saturday";System.out.println("Today is " + nameForToday+ " and the future day is " + nameForFutureDay); } }3.6public class Exercise03_06 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter weight in pounds System.out.print("Enter weight in pounds: "); double weight = input.nextDouble();// Prompt the user to enter heightSystem.out.print("Enter feet: ");double feet = input.nextDouble();System.out.print("Enter inches: ");double inches = input.nextDouble();double height = feet * 12 + inches;// Compute BMIdouble bmi = weight * 0.45359237 / ((height * 0.0254) * (height * 0.0254));// Display resultSystem.out.println("BMI is " + bmi);if (bmi < 18.5)System.out.println("Underweight");else if (bmi < 25)System.out.println("Normal");else if (bmi < 30)System.out.println("Overweight");elseSystem.out.println("Obese");}}3.7/** Break down an amount into smaller units* Display the non-zero denominations only, and display singular* words for single units like 1 dollars, 1 penny, and display plural * words for more than one unit like 2 dollars, 3 pennies.*/public class Exercise03_07 {// Main methodpublic static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Receive the amount entered from the keyboardSystem.out.print("Enter an amount in double, for example 11.56: ");double amount = input.nextDouble();int remainingAmount = (int)(amount * 100);// Find the number of one dollarsint numberOfOneDollars = remainingAmount / 100;remainingAmount = remainingAmount % 100;// Find the number of quarters in the remaining amountint numberOfQuarters = remainingAmount / 25;remainingAmount = remainingAmount % 25;// Find the number of dimes in the remaining amountint numberOfDimes = remainingAmount / 10;remainingAmount = remainingAmount % 10;// Find the number of nickels in the remaining amountint numberOfNickels = remainingAmount / 5;remainingAmount = remainingAmount % 5;// Find the number of pennies in the remaining amountint numberOfPennies = remainingAmount;// Display resultsif (amount < 0) {System.out.println("Your amount is negative");System.exit(1);}else if (amount < 0) {System.out.println("Your amount is zero");System.exit(2);}System.out.println("Your amount " + amount + " consists of ");if (numberOfOneDollars > 1)System.out.println(numberOfOneDollars + "\ dollars");else if (numberOfOneDollars == 1)System.out.println(numberOfOneDollars + "\ dollar");if (numberOfQuarters > 1)System.out.println(numberOfQuarters + "\ quarters");else if (numberOfQuarters == 1)System.out.println(numberOfQuarters + "\ quarter");if (numberOfDimes > 1)System.out.println(numberOfDimes + "\ dimes");else if (numberOfDimes == 1)System.out.println(numberOfDimes + "\ dime");if (numberOfNickels > 1)System.out.println(numberOfNickels + "\ nickels");else if (numberOfNickels == 1)System.out.println(numberOfNickels + "\ nickel");if (numberOfPennies > 1)System.out.println(numberOfPennies + "\ pennies");else if (numberOfPennies == 1)System.out.println(numberOfPennies + "\ penny");}}3.8public class Exercise03_08 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in); // Enter three numbersSystem.out.print("Enter three integers: ");int number1 = input.nextInt();int number2 = input.nextInt();int number3 = input.nextInt();if (number1 > number2) {int temp = number1;number1 = number2;number2 = temp;}if (number2 > number3) {int temp = number2;number2 = number3;number3 = temp;}if (number1 > number2) {int temp = number1;number1 = number2;number2 = temp;}System.out.println("The sorted numbers are "+ number1 + " " + number2 + " " + number3);}}public class Exercise03_09 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter an integerSystem.out.print("Enter the first 9 digits of an ISBN as integer: ");int number = input.nextInt();// Calculate checksum (You may write a loop to simplify it in Ch4int checksum =((number / 100000000 % 10) * 1 +(number / 10000000 % 10) * 2 +(number / 1000000 % 10) * 3 +(number / 100000 % 10) * 4 +(number / 10000 % 10) * 5 +(number / 1000 % 10) * 6 +(number / 100 % 10) * 7 +(number / 10 % 10) * 8 +(number % 10) * 9) % 11;System.out.print("The ISBN-10 number is ");// Display leading zeros, improve the solution using loops in the next chapterif (number / 100000000 == 0) {System.out.print("0");if (number / 10000000 == 0) {System.out.print("0");if (number / 1000000 == 0) {System.out.print("0");if (number / 100000 == 0) {System.out.print("0");if (number / 10000 == 0) { System.out.print("0");if (number / 1000 == 0) { System.out.print("0");if (number / 100 == 0) {System.out.print("0");if (number / 10 == 0) {System.out.print("0");if (number == 0) {System.out.print("0");}}}}}}}}}System.out.print(number);if (checksum == 10)System.out.print("X");elseSystem.out.print(checksum);}}3.10public class Exercise03_10 {public static void main(String[] args) {// 1. Generate two random single-digit integersint number1 = (int)(Math.random() * 10);int number2 = (int)(Math.random() * 10);// 2. Prompt the student to answer 搘hat is number1 + number2?? System.out.print("What is " + number1 + " + " + number2 + "? "); Scanner input = new Scanner(System.in);int answer = input.nextInt();// 4. Grade the answer and display the resultString replyString;if (number1 + number2 == answer)replyString = "You are correct!";elsereplyString = "Your answer is wrong.\" + number1 + " + "+ number2 + " should be " + (number1 + number2);System.out.println(replyString);}}3.11public class Exercise03_11 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter inputSystem.out.print("Enter a month in the year (e.g., 1 for Jan): ");int month = input.nextInt();System.out.print("Enter a year: ");int year = input.nextInt();int numberOfDaysInMonth = 0;switch (month) {case 1:System.out.print("January " + year);numberOfDaysInMonth = 31;break;case 2:System.out.print("February " + year);if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) { numberOfDaysInMonth = 29;}else {numberOfDaysInMonth = 28;}break;case 3:System.out.print("March " + year);numberOfDaysInMonth = 31;break;case 4:System.out.print("April " + year);numberOfDaysInMonth = 30;break;case 5:System.out.print("May " + year);numberOfDaysInMonth = 31;break;case 6:System.out.print("June " + year);numberOfDaysInMonth = 30;break;case 7:System.out.print("July " + year);numberOfDaysInMonth = 31;break;case 8:System.out.print("August " + year);numberOfDaysInMonth = 31;break;case 9:System.out.print("September " + year);numberOfDaysInMonth = 30;break;case 10:System.out.print("October " + year);numberOfDaysInMonth = 31;break;case 11:System.out.print("November " + year);numberOfDaysInMonth = 30;break;case 12:System.out.print("December " + year);numberOfDaysInMonth = 31;break;}System.out.print(" has " + numberOfDaysInMonth + " days"); }}3.12public class Exercise03_12 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a three-digit integer: ");int number = input.nextInt();if (number / 100 == number % 10)System.out.println(number + " is a palindrome");elseSystem.out.println(number + " is not a palindrome");}}3.13public class Exercise03_13 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter filing statusSystem.out.print("(0-single filer, 1-married jointly or qualifying widow(er),"+ "\2-married separately, 3-head of household)\" + "Enter the filing status: ");int status = input.nextInt();// Prompt the user to enter taxable incomeSystem.out.print("Enter the taxable income: ");double income = input.nextDouble();// Compute taxdouble tax = 0;if (status == 0) { // Compute tax for single filersif (income <= 8350) {tax = income * 0.10;} else if (income <= 33950) {tax = 8350 * 0.10 + (income - 8350) * 0.15;} else if (income <= 82250) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950)* 0.25; } else if (income <= 171550) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (income - 82250) * 0.28;} else if (income <= 372950) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (income - 171550) * 0.33;} else {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (372950 - 171550) * 0.33 + (income - 372950) * 0.35;}} else if (status == 1) { // Compute tax for married file jointly if (income <= 16700) {tax = income * 0.10;} else if (income <= 67900) {tax = 16700 * 0.10 + (income - 16700) * 0.15;} else if (income <= 137050) {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (income - 67900) * 0.25; } else if (income <= 208850) {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (income - 137050) * 0.28;} else if (income <= 372950) {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (208850 - 137050) * 0.28 + (income - 208850) * 0.33;} else {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (171950 - 137050) * 0.28 + (372950 - 208850) * 0.33+ (income - 372950) * 0.35;}} else if (status == 2) { // Compute tax for married separately if (income <= 8350) {tax = income * 0.10;} else if (income <= 33950) {tax = 8350 * 0.10 + (income - 8350) * 0.15;} else if (income <= 68525) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950) * 0.25; } else if (income <= 104425) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (income - 68525) * 0.28;} else if (income <= 186475) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (104425 - 68525) * 0.28 + (income - 104425) * 0.33;} else {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (104425 - 68525) * 0.28 + (186475 - 104425) * 0.33 + (income - 186475) * 0.35;}} else if (status == 3) { // Compute tax for head of household if (income <= 11950) {tax = income * 0.10;} else if (income <= 45500) {tax = 11950 * 0.10 + (income - 11950) * 0.15;} else if (income <= 117450) {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (income - 45500) * 0.25; } else if (income <= 190200) {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (income - 117450) * 0.28;} else if (income <= 372950) {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (190200 - 117450) * 0.28 + (income - 190200) * 0.33;} else {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (190200 - 117450) * 0.28 + (372950 - 190200) * 0.33+ (income - 372950) * 0.35;}} else {System.out.println("Error: Wrong filing status");System.exit(1);}// Display the resultSystem.out.println("Tax is " + (int) (tax * 100) / 100.0);}}3.14public class Exercise03_14 {public static void main(String[] args) {// Obtain the random number 0 or 1int number = (int)(Math.random() * 2);// Prompt the user to enter a guessjava.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Guess head or tail? " +"Enter 0 for head and 1 for tail: ");int guess = input.nextInt();// Check the guessif (guess == number)System.out.println("Correct guess");else if (number == 0)System.out.println("Sorry, it is a head");elseSystem.out.println("Sorry, it is a tail");}}3.15public class Exercise03_15 {public static void main(String[] args) {// Generate a lotteryint lottery = (int)(Math.random() * 1000);// Prompt the user to enter a guessjava.util.Scanner input = new java.util.Scanner(System.in); System.out.print("Enter your lottery pick (three digits): ");int guess = input.nextInt();// Get digitsint l1 = lottery / 100;int l2 = (lottery % 100) / 10; // l2 = (lottery / 10) % 10int l3 = lottery % 10;int g1 = guess / 100;int g2 = (guess % 100) / 10;int g3 = guess % 10;System.out.println("Lottery is " + lottery);// Check the guessif (guess == lottery)System.out.println("Exact match: you win $10,000");else if (g1 == l1 && g3 == l2 && g2 == l3 ||g2 == l1 && g1 == l2 && g3 == l3 ||g2 == l1 && g3 == l2 && g1 == l3 ||g3 == l1 && g1 == l2 && g2 == l3 ||g3 == l1 && g2 == l2 && g1 == l3)System.out.println("Match all digits: you win $3,000"); else if (g1 == l1 || g1 == l2 || g1 == l3 ||g2 == l1 || g2 == l2 || g2 == l3 ||g3 == l1 || g3 == l2 || g3 == l3)System.out.println("Match one digit: you win $1,000"); elseSystem.out.println("Sorry, no match");}}3.16public class Exercise03_16 {public static void main(String[] args) {double x = Math.random() * 100 - 50;double y = Math.random() * 200 - 100;System.out.println(x + ", " + y);}}3.17public class Exercise03_17 {public static void main(String[] args) {// Generate scissor, rock, paperint computerNumber = (int)(Math.random() * 3);// Prompt the user to enter scissor, rock, or paper java.util.Scanner input = new java.util.Scanner(System.in); System.out.print("scissor (0), rock (1), paper (2): ");int userNumber = input.nextInt();// Check the guessswitch (computerNumber) {case 0:if (userNumber == 0)System.out.print("The computer is scissor. You are scissor too. It is a draw");else if (userNumber == 1)System.out.print("The computer is scissor. You are rock. You won");else if (userNumber == 2)System.out.print("The computer is scissor. You are paper. You lost");break;case 1:if (userNumber == 0)System.out.print("The computer is rock. You are scissor. You lost");else if (userNumber == 1)System.out.print("The computer is rock. You are rock too. It is a draw");else if (userNumber == 2)System.out.print("The computer is rock. You are paper. You won");break;case 2:if (userNumber == 0)System.out.print("The computer is paper. You are scissor. You won");else if (userNumber == 1)System.out.print("The computer is paper. You are rock. You lost");else if (userNumber == 2)System.out.print("The computer is paper. You are paper too.It is a draw");break;}}}3.18public class Exercise03_18 {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter package weight: ");double w = input.nextDouble();if (w <= 1) {System.out.println("The shipping cost is $3.5");}else if (w <= 3) {System.out.println("The shipping cost is $5.5");}else if (w <= 10) {System.out.println("The shipping cost is $8.5");}else if (w <= 20) {System.out.println("The shipping cost is $10.5");}else {System.out.println("The package cannot be shipped");}}}3.19public class Exercise03_19 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in); // Enter three edgesSystem.out.print("Enter three edges (length in double): ");double edge1 = input.nextDouble();double edge2 = input.nextDouble();double edge3 = input.nextDouble();。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
《Java语言程序设计(基础篇)》(第10版梁勇著)第八章练习题答案8.1public class Exercise08_01 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a 3 by 4 matrix row by row: ");double[][] m = new double[3][4];for (int i = 0; i < m.length; i++)for (int j = 0; j < m[i].length; j++)m[i][j] = input.nextDouble();for (int j = 0; j < m[2].length; j++) {System.out.println("Sum of the elements at column " + j + " is " + sumColumn(m, j));}}public static double sumColumn(double[][] m, int columnIndex) {double total = 0;for (int i = 0; i < m.length; i++)total += m[i][columnIndex];return total;}}8.1附加public class Exercise08_01Extra {public static void main(String[] args) {final int N = 2;Scanner input = new Scanner(System.in);double[][] A = new double[N][N];System.out.print("Enter a, b, c, d: ");A[0][0] = input.nextDouble();A[0][1] = input.nextDouble();A[1][0] = input.nextDouble();A[1][1] = input.nextDouble();double[][] inverseA = inverse(A);if (inverseA == null)System.out.println("No inverse matrix");elseprintMatrix(inverse(A));}public static void printMatrix(double[][] A) {for (int i = 0; i < A.length; i++) {for (int j = 0; j < A.length; j++)System.out.print(A[i][j] + " ");System.out.println();}}public static double[][] inverse(double[][] A) {double[][] result = new double[A.length][A.length];double determinant = A[0][0] * A[1][1] - A[0][1] * A[1][0];if (determinant == 0)return null;result[0][0] = A[1][1] / determinant;result[0][1] = -A[0][1] / determinant;result[1][0] = -A[1][0] / determinant;result[1][1] = A[0][0] / determinant;return result;}}8.2public class Exercise08_02 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a 4 by 4 matrix row by row: ");double[][] m = new double[4][4];for (int i = 0; i < 4; i++)for (int j = 0; j < 4; j++)m[i][j] = input.nextDouble();System.out.print("Sum of the elements in the major diagonal is "+ sumMajorDiagonal(m));}public static double sumMajorDiagonal(double[][] m) {double sum = 0;for (int i = 0; i < m.length; i++)sum += m[i][i];return sum;}}8.2附加public class Exercise08_02Extra {final static int N = 3;public static void main(String[] args) {double[][] A = new double[N][N];System.out.print("Enter a11, a12, a13, a21, a22, a23, a31, a32, a33: ");Scanner input = new Scanner(System.in);A[0][0] = input.nextDouble();A[0][1] = input.nextDouble();A[0][2] = input.nextDouble();A[1][0] = input.nextDouble();A[1][1] = input.nextDouble();A[1][2] = input.nextDouble();A[2][0] = input.nextDouble();A[2][1] = input.nextDouble();A[2][2] = input.nextDouble();System.out.print("Enter b1, b2, b3: ");double[] B = new double[3];B[0] = input.nextDouble();B[1] = input.nextDouble();B[2] = input.nextDouble();double[] result = getSolution(A, B);if (result == null)System.out.println("No solution");else {System.out.println("The solution is " + result[0] + " " + result[1] + " " + result[2]);}}public static double deltaA(double[][] A) {double result = A[0][0] * A[1][1] * A[2][2] +A[2][0] * A[0][1] * A[1][2] + A[0][2] * A[1][0] * A[2][1] -A[0][2] * A[1][1] * A[2][0] - A[0][0] * A[1][2] * A[2][1] -A[2][2] * A[1][0] * A[0][1];return result;}public static double[] getSolution(double[][] A, double[] B) {double delta = deltaA(A);if (delta == 0)return null;else {double x = ((A[1][1] * A[2][2] - A[1][2] * A[2][1]) * B[0] +(A[0][2] * A[2][1] - A[0][1] * A[2][2]) * B[1] +(A[0][1] * A[1][2] - A[0][2] * A[1][1]) * B[2]) / delta;double y = ((A[1][2] * A[2][0] - A[1][0] * A[2][2]) * B[0] +(A[0][0] * A[2][2] - A[0][2] * A[2][0]) * B[1] +(A[0][2] * A[1][0] - A[0][0] * A[1][2]) * B[2]) / delta;double z = ((A[1][0] * A[2][1] - A[1][1] * A[2][0]) * B[0] +(A[0][1] * A[2][0] - A[0][0] * A[2][1]) * B[1] +(A[0][0] * A[1][1] - A[0][1] * A[1][0]) * B[2]) / delta;return new double[]{x, y, z};}}}8.3public class Exercise08_03 {public static void main(String args[]) {// Students' answers to the questionschar[][] answers = {{'A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},{'D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'},{'E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D'},{'C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D'},{'A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},{'B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},{'B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},{'E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}};// Key to the questionschar[] keys = {'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D'};int[] correctCounts = new int[answers.length];// Grade all answersfor (int i = 0; i < answers.length; i++) {// Grade one studentfor (int j = 0; j < answers[i].length; j++) {if (answers[i][j] == keys[j])correctCounts[i]++;}}int[] indexList = new int[answers.length];// Sort totalScoressortAndKeepIndex(correctCounts, indexList);// Display resultfor (int i = 0; i < correctCounts.length; i++)System.out.println("Student " + indexList[i] + ": " +correctCounts[i]);System.out.println("Mean is " + Deviation.mean(correctCounts));System.out.println("Deviation is "+ Deviation.deviation(correctCounts)); }/** The method for sorting the numbers */static void sortAndKeepIndex(int[] list, int[] indexList) {int currentMax;int currentMaxIndex;// Initialize indexListfor (int i = 0; i < indexList.length; i++)indexList[i] = i;for (int i = list.length - 1; i >= 1; i--) {// Find the maximum in the list[0..i]currentMax = list[i];currentMaxIndex = i;for (int j = i - 1; j >= 0; j--) {if (currentMax < list[j]) {currentMax = list[j];currentMaxIndex = j;}}// Swap list[i] with list[currentMaxIndex] if necessary;if (currentMaxIndex != i) {list[currentMaxIndex] = list[i];list[i] = currentMax;// Swap the index in indexList tooint temp = indexList[i];indexList[i] = indexList[currentMaxIndex];indexList[currentMaxIndex] = temp;}}}}8.3附加public class Exercise08_03Extra {public static void main(String[] args) {final int N = 3;Scanner input = new Scanner(System.in);double[][] A = new double[N][N];System.out.print("Enter a11, a12, a13, a21, a22, a23, a31, a32, a33: "); A[0][0] = input.nextDouble();A[0][1] = input.nextDouble();A[0][2] = input.nextDouble();A[1][0] = input.nextDouble();A[1][1] = input.nextDouble();A[1][2] = input.nextDouble();A[2][0] = input.nextDouble();A[2][1] = input.nextDouble();A[2][2] = input.nextDouble();double[][] inverseA = inverse(A);if (inverseA == null)System.out.println("No inverse matrix");elsedisplayMatrix(inverseA);}public static void displayMatrix(double[][] A) {for (int i = 0; i < A.length; i++) {for (int j = 0; j < A.length; j++)System.out.print(A[i][j] + " ");System.out.println();}}public static double deltaA(double[][] A) {double result = A[0][0] * A[1][1] * A[2][2] +A[2][0] * A[0][1] * A[1][2] + A[0][2] * A[1][0] * A[2][1] -A[0][2] * A[1][1] * A[2][0] - A[0][0] * A[1][2] * A[2][1] -A[2][2] * A[1][0] * A[0][1];return result;}public static double[][] inverse(double[][] A) {double[][] result = new double[A.length][A.length];double determinant = deltaA(A);result[0][0] = (A[1][1] * A[2][2] - A[1][2] * A[2][1]) / determinant; result[0][1] = (A[0][2] * A[2][1] - A[0][1] * A[2][2]) / determinant; result[0][2] = (A[0][1] * A[1][2] - A[0][2] * A[1][1]) / determinant; result[1][0] = (A[1][2] * A[2][0] - A[1][0] * A[2][2]) / determinant; result[1][1] = (A[0][0] * A[2][2] - A[0][2] * A[2][0]) / determinant; result[1][2] = (A[0][2] * A[1][0] - A[0][0] * A[1][2]) / determinant; result[2][0] = (A[1][0] * A[2][1] - A[1][1] * A[2][0]) / determinant; result[2][1] = (A[0][1] * A[2][0] - A[0][0] * A[2][1]) / determinant; result[2][2] = (A[0][0] * A[1][1] - A[0][1] * A[1][0]) / determinant;return result;}}8.4public class Exercise08_04 {/** Main method */public static void main(String args[]) {// Declare, create, and initialized arraydouble[][] workHours = {{2, 4, 3, 4, 5, 8, 8},{7, 3, 4, 3, 3, 4, 4},{3, 3, 4, 3, 3, 2, 2},{9, 3, 4, 7, 3, 4, 1},{3, 5, 4, 3, 6, 3, 8},{3, 4, 4, 6, 3, 4, 4},{3, 7, 4, 8, 3, 8, 4},{6, 3, 5, 9, 2, 7, 9}};// Create an array to store total weekly hoursint[] weeklyHours = new int[workHours.length];for (int i = 0; i < workHours.length; i++)for (int j = 0; j < workHours[i].length; j++)weeklyHours[i] += workHours[i][j];int[] indexList = new int[weeklyHours.length];// Sort weeklyHourssortAndKeepIndex(weeklyHours, indexList);// Display resultfor (int i = weeklyHours.length - 1; i >= 0; i--)System.out.println("Employee " + indexList[i] + ": " + weeklyHours[i]);}/** The method for sorting the numbers */static void sortAndKeepIndex(int[] list, int[] indexList) { int currentMax;int currentMaxIndex;// Initialize indexListfor (int i = 0; i < indexList.length; i++)indexList[i] = i;for (int i = list.length - 1; i >= 1; i--) {// Find the maximum in the list[0..i]currentMax = list[i];currentMaxIndex = i;for (int j = i - 1; j >= 0; j--) {if (currentMax < list[j]) {currentMax = list[j];currentMaxIndex = j;}}// Swap list[i] with list[currentMaxIndex] if necessary;if (currentMaxIndex != i) {list[currentMaxIndex] = list[i];list[i] = currentMax;// Swap the index in indexList tooint temp = indexList[i];indexList[i] = indexList[currentMaxIndex];indexList[currentMaxIndex] = temp;}}}}8.5public class Exercise08_05 {/** Main method */public static void main(String[] args) {Scanner input = new Scanner(System.in);final int N = 3;final int M = 3;// Enter matrix1System.out.print("Enter matrix1: ");double[][] matrix1 = new double[N][M];for (int i = 0; i < matrix1.length; i++)for (int j = 0; j < matrix1[i].length; j++) {matrix1[i][j] = input.nextDouble();}// Enter matrix2System.out.print("Enter matrix2: ");double[][] matrix2 = new double[N][M];for (int i = 0; i < matrix1.length; i++)for (int j = 0; j < matrix1[i].length; j++) {matrix2[i][j] = input.nextDouble();}// Add two matrices and print the resultdouble[][] resultMatrix = addMatrix(matrix1, matrix2);System.out.println("The addition of the matrices is ");printResult(matrix1, matrix2, resultMatrix, '+');}/** The method for adding two matrices */public static double[][] addMatrix(double[][] m1, double[][] m2) { double[][] result = new double[m1.length][m1[0].length];for (int i = 0; i < result.length; i++)for (int j = 0; j < result[i].length; j++)result[i][j] = m1[i][j] + m2[i][j];return result;}/** Print result */public static void printResult(double[][] m1, double[][] m2, double[][] 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[0].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[0].length; j++)System.out.print(" " + m3[i][j]);System.out.println();}}}8.6public class Exercise08_06 {/** Main method */public static void main(String[] args) {Scanner input = new Scanner(System.in);final int N = 3;// Enter matrix1System.out.print("Enter matrix1: ");double[][] matrix1 = new double[N][N];for (int i = 0; i < matrix1.length; i++)for (int j = 0; j < matrix1[i].length; j++) {matrix1[i][j] = input.nextDouble();}// Enter matrix2System.out.print("Enter matrix2: ");double[][] matrix2 = new double[N][N];for (int i = 0; i < matrix1.length; i++)for (int j = 0; j < matrix1[i].length; j++) {matrix2[i][j] = input.nextDouble();}// Multiply two matrices and print the resultdouble[][] resultMatrix = multiplyMatrix(matrix1, matrix2);System.out.println("\nThe multiplication of the matrices is "); printResult(matrix1, matrix2, resultMatrix, '*');}/** The method for multiplying two matrices */public static double[][] multiplyMatrix(double[][] m1, double[][] m2) {double[][] result = new double[m1.length][m2[0].length];for (int i = 0; i < m1.length; i++)for (int j = 0; j < result.length; j++)for (int k = 0; k < result[0].length; k++)result[i][j] += m1[i][k] * m2[k][j];return result;}/** Print result */public static void printResult(double[][] m1, double[][] m2, double[][] 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[0].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[0].length; j++)System.out.print(" " + m3[i][j]);System.out.println();}}}8.7public class Exercise08_07 {public static void main(String[] args) {// Each row in points represents a pointdouble[][] points = {{-1, 0, 3}, {-1, -1, -1}, {4, 1, 1},{2, 0.5, 9}, {3.5, 2, -1}, {3, 1.5, 3}, {-1.5, 4, 2},{5.5, 4, -0.5}};// p1 and p2 are the indices in the points arrayint p1 = 0, p2 = 1; // Initial two pointsdouble shortestDistance = distance(points[p1][0], points[p1][1], points[p1][2],points[p2][0], points[p2][1], points[p2][2]); // 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][0], points[i][1], points[i][2],points[j][0], points[j][1], points[j][2]);if (shortestDistance > distance) {p1 = i; // Update p1p2 = j; // Update p2shortestDistance = distance; // Update shortestDistances}}}// Display resultSystem.out.println("The closest two points are " +"(" + points[p1][0] + ", " + points[p1][1] + ", " + points[p1][2] + ") and (" +points[p2][0] + ", " + points[p2][1] + ", " + points[p2][2] + ")");}/** Compute the distance between two points */public static double distance(double x1, double y1, double z1, double x2, double y2, double z2) { return Math.sqrt((x2 - x1) * (x2 - x1)+ (y2 - y1) * (y2 - y1) + (z2 - z1) * (z2 - z1));}}8.8public class Exercise08_08 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter the number of points: ");int numberOfPoints = input.nextInt();// Create an array to store pointsdouble[][] points = new double[numberOfPoints][2];System.out.print("Enter " + numberOfPoints + " points: ");for (int i = 0; i < points.length; i++) {points[i][0] = input.nextDouble();points[i][1] = input.nextDouble();}// p1 and p2 are the indices in the points arrayint p1 = 0, p2 = 1; // Initial two pointsdouble shortestDistances = distance(points[p1][0], points[p1][1], points[p2][0], points[p2][1]); // Initialize shortestDistances// Store a closest pair in (indices[i][0], indices[i][1])// The pair of the points for (indices[i][0], indices[i][1]) is// points[indices[i][0]] and points[indices[i][1]]int[][] indices = new int[points.length][2];int k = 0;// 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][0], points[i][1],points[j][0], points[j][1]); // Find distanceif (distance < shortestDistances) {// Add a closest pairk = 0; // Reset k for new closest pairsindices[k][0] = i;indices[k][1] = j;shortestDistances = distance; // Update shortestDistances}else if (distance == shortestDistances) {// Add another closest pair with the same minimum distanceindices[k][0] = i;indices[k][1] = j;k++;}}}// Display all closest pairsfor (int i = 0; i < k; i++) {p1 = indices[i][0]; p2 = indices[i][1];System.out.println("The closest two points are " +"(" + points[p1][0] + ", " + points[p1][1] + ") and (" +points[p2][0] + ", " + points[p2][1] + ")");}System.out.println("Their distance is " + shortestDistances);}/** Compute the distance between two 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)); }}8.9public class Exercise08_09 {public static void main(String[] args) {char[][] board = new char[3][3];displayBoard(board);while (true) {// Prompt the first playermakeAMove(board, 'X');displayBoard(board);if (isWon('X', board)) {System.out.println("X player won");System.exit(1);}else if (isDraw(board)) {System.out.println("No winner");System.exit(2);}// Prompt the second playermakeAMove(board, 'O');displayBoard(board);if (isWon('O', board)) {System.out.println("O player won");System.exit(3);}else if (isDraw(board)) {System.out.println("No winner");System.exit(4);}}public static void makeAMove(char[][] board, char player) {Scanner input = new Scanner(System.in);boolean done = false;do {System.out.print("Enter a row for player " + player + ": ");int row = input.nextInt();System.out.print("Enter a column for player " + player + ": ");int column = input.nextInt();if (board[row][column] == '\u0000') { // an empty cellboard[row][column] = player;done = true;}elseSystem.out.println("This cell is already occupied. Try a different cell");}while (!done);}static void displayBoard(char[][] board) {System.out.println("\n-------------");for (int i = 0; i < 3; i++) {System.out.print("| ");for (int j = 0; j < 3; j++)System.out.print(board[i][j] != '\u0000' ? board[i][j] + " | ": " | ");System.out.println("\n-------------");}}public static boolean isWon(char ch, char[][] board) {// Check rowsfor (int i = 0; i < 3; i++)if (ch == board[i][0] && ch == board[i][1] && ch == board[i][2]) return true;// Check columnsfor (int j = 0; j < 3; j++)if (ch == board[0][j] && ch == board[1][j] && ch == board[2][j]) return true;// Check major diagonalif(ch == board[0][0] && ch == board[1][1] && ch == board[2][2]) return true;// Check sub diagonalif(ch == board[0][2] && ch == board[1][1] && ch == board[2][0]) return true;return false;}public static boolean isDraw(char[][] board) {for (int i = 0; i < 3; i++)for (int j = 0; j < 3; j++)if (board[i][j] == '\u0000') return false;return true; // All cells are now occupied}}8.10public class Exercise08_10 {public static void main(String[] args) {final int n = 4;int[][] matrix = new int[n][n];for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {matrix[i][j] = (int)(Math.random() * 2);System.out.print(matrix[i][j]);}System.out.println();}// Check rowsint rowSum = sumRow(matrix[0]);int rowIndex = 0;for (int i = 1; i < n; i++) {if (rowSum < sumRow(matrix[i])) {rowSum = sumRow(matrix[i]);rowIndex = i;}}System.out.println("The largest row index: " + rowIndex);// Check columnsint columnSum = sumColumn(matrix, 0);int columnIndex = 0;for (int i = 1; i < n; i++) {if (columnSum < sumColumn(matrix, i)) {columnSum = sumColumn(matrix, i);columnIndex = i;}}System.out.println("The largest column index: " + columnIndex); }public static int sumRow(int row[]) {int sum = 0;for (int i = 0; i < row.length; i++)sum += row[i];return sum;}public static int sumColumn(int matrix[][], int column) {int sum = 0;for (int i = 0; i < matrix.length; i++)sum += matrix[i][column];return sum;}}8.11public class Exercise08_11 {public static void main(String[] args) {System.out.print("Enter a number between 0 and 511: ");Scanner input = new Scanner(System.in);short number = input.nextShort();char[] binaryChars = toBinaryChars(number);for (int i = 1; i <= binaryChars.length; i++) {System.out.print(((binaryChars[i - 1] == '0')?'H':'T') + " ");if (i % 3 == 0)System.out.println();}}public static char[] toBinaryChars(short number) {char[] result = new char[9];int i = result.length - 1;while (number != 0) {if (number % 2 == 0)result[i--] = '0';elseresult[i--] = '1';number /= 2;}for (int k = i; k >= 0; k--)result[k] = '0';return result;}}8.12public class Exercise08_12 {public static void main(String[] args) {// Create a ScannerScanner input = new Scanner(System.in);// Prompt the user to enter filing status// Prompt the user to enter filing statusSystem.out.print("(0-single filer, 1-married jointly,\n" +"2-married separately, 3-head of household)\n" +"Enter the filing status: ");int status = input.nextInt();// Prompt the user to enter taxable incomeSystem.out.print("Enter the taxable income: ");double income = input.nextDouble();// Compute and display the resultif (status >= 0 && status <= 3)System.out.println("Tax is " +(int)(computeTax(status, income) * 100) / 100.0);elseSystem.out.println("Error: invalid input");}public static double computeTax(int status, double income) { double[] rates = {0.10, 0.15, 0.25, 0.28, 0.33, 0.35};int[][] brackets = {{8350, 33950, 82250, 171550, 372950}, // Single filer{16700, 67900, 137050, 20885, 372950}, // Married jointly{8350, 33950, 68525, 104425, 186475}, // Married separately{11950, 45500, 117450, 190200, 372950} // Head of household};double tax = 0; // Tax to be computed// Compute tax in the first bracketif (income <= brackets[status][0])return tax = income * rates[0]; // Doneelsetax = brackets[status][0] * rates[0];// Compute tax in the 2nd, 3rd, 4th, and 5th brackets, if neededfor (int i = 1; i < brackets[0].length; i++) {if (income > brackets[status][i])tax += (brackets[status][i] - brackets[status][i - 1]) *rates[i];else {tax += (income - brackets[status][i - 1]) * rates[i];return tax; // Done}}// Compute tax in the last (i.e., 6th) bracketreturn tax += (income - brackets[status][4]) * rates[5];}}8.13public class Exercise08_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();int[] location = locateLargest(a);System.out.println("The location of the largest element is at (" + location[0] + ", " + location[1] + ")");}public static int[] locateLargest(double[][] a) {int[] location = new int[2];double largest = a[0][0];for (int i = 0; i < a.length; i++)for (int j = 0; j < a[i].length; j++) {if (largest < a[i][j]) {largest = a[i][j];location[0] = i;location[1] = j;}}return location;}}8.14public class Exercise08_14 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter the length of a square matrix: ");int n = input.nextInt();int[][] board = new int[n][n];boolean isSameOnARow = false, isSameOnAColumn = false,isSameOnADiagonal = false, isSameOnASubdiagonal = false;for (int i = 0; i < board.length; i++) {for (int j = 0; j < board[0].length; j++) {board[i][j] = (int) (Math.random() * 2);System.out.print(board[i][j]);}System.out.println();}// Check rowsfor (int i = 0; i < board.length; i++) {boolean same = true;for (int j = 1; j < board[0].length; j++) {if (board[i][0] != board[i][j]) {same = false;break;}}if (same) {System.out.println("All " + board[i][0] + "'s on row " + i);isSameOnARow = true;}}// Check columnsfor (int j = 0; j < board[0].length; j++) {boolean same = true;for (int i = 1; i < board.length; i++) {if (board[0][j] != board[i][j]) {same = false;break;}}if (same) {System.out.println("All " + board[0][j] + "'s on column " + j); isSameOnAColumn = true;}。