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

合集下载

梁勇java第十版复习题答案

梁勇java第十版复习题答案

梁勇java第十版复习题答案1. 简述Java中接口和抽象类的区别。

接口是一种完全抽象的类,可以包含抽象方法和默认方法,不能包含实现细节,而抽象类可以包含抽象方法和具体方法,可以包含成员变量和方法实现。

2. 描述Java中多态的实现机制。

多态的实现依赖于方法的重载和重写。

重载是指在同一个类中定义多个同名方法,但参数列表不同;重写是指子类中定义一个与父类同名的方法,并且参数列表相同。

3. 如何在Java中实现单例模式?单例模式可以通过私有构造函数、私有静态实例和公有静态方法来实现。

私有构造函数防止外部实例化,私有静态实例确保只创建一个对象,公有静态方法提供全局访问点。

4. 解释Java中的垃圾回收机制。

垃圾回收是Java自动管理内存的一种机制,它通过识别不再使用的对象并释放其占用的内存空间来防止内存泄漏。

垃圾回收器会定期执行,但具体的执行时机和方式由JVM控制。

5. 描述Java中异常处理的流程。

异常处理包括try、catch和finally块。

try块中放置可能抛出异常的代码,catch块捕获并处理异常,finally块中的代码无论是否发生异常都会执行,常用于资源清理。

6. 简述Java集合框架中的List、Set和Map的区别。

List是一个有序集合,允许重复元素;Set是一个无序集合,不允许重复元素;Map是一个键值对集合,键不允许重复,值可以重复。

7. 如何在Java中实现线程同步?线程同步可以通过synchronized关键字、Lock接口和volatile关键字来实现。

synchronized关键字可以修饰方法或代码块,保证同一时间只有一个线程访问;Lock接口提供了更灵活的锁定机制;volatile关键字确保变量的可见性和有序性。

8. 描述Java中泛型的作用。

泛型提供了一种类型安全的方式,允许在编译时检查类型错误,避免了类型转换的麻烦,并提高了代码的重用性。

9. 简述Java中I/O流的分类。

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

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

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

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

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

《Java语言程序设计(基础篇)》(第10版梁勇著)第九章练习题答案9.1public class Exercise09_01 {public static void main(String[] args) {MyRectangle myRectangle = new MyRectangle(4, 40);System.out.println("The area of a rectangle with width " +myRectangle.width + " and height " +myRectangle.height + " is " +myRectangle.getArea());System.out.println("The perimeter of a rectangle is " +myRectangle.getPerimeter());MyRectangle yourRectangle = new MyRectangle(3.5, 35.9);System.out.println("The area of a rectangle with width " +yourRectangle.width + " and height " +yourRectangle.height + " is " +yourRectangle.getArea());System.out.println("The perimeter of a rectangle is " +yourRectangle.getPerimeter());}}class MyRectangle {// Data membersdouble width = 1, height = 1;// Constructorpublic MyRectangle() {}// Constructorpublic MyRectangle(double newWidth, double newHeight) {width = newWidth;height = newHeight;}public double getArea() {return width * height;}public double getPerimeter() {return 2 * (width + height);}}9.2public class Exercise09_02 {public static void main(String[] args) {Stock stock = new Stock("SUNW", "Sun MicroSystems Inc."); stock.setPreviousClosingPrice(100);// Set current pricestock.setCurrentPrice(90);// Display stock infoSystem.out.println("Previous Closing Price: " +stock.getPreviousClosingPrice());System.out.println("Current Price: " +stock.getCurrentPrice());System.out.println("Price Change: " +stock.getChangePercent() * 100 + "%");}}class Stock {String symbol;String name;double previousClosingPrice;double currentPrice;public Stock() {}public Stock(String newSymbol, String newName) {symbol = newSymbol;name = newName;}public double getChangePercent() {return (currentPrice - previousClosingPrice) /previousClosingPrice;}public double getPreviousClosingPrice() {return previousClosingPrice;}public double getCurrentPrice() {return currentPrice;}public void setCurrentPrice(double newCurrentPrice) {currentPrice = newCurrentPrice;}public void setPreviousClosingPrice(double newPreviousClosingPrice) { previousClosingPrice = newPreviousClosingPrice;}}9.3public class Exercise09_03 {public static void main(String[] args) {Date date = new Date();int count = 1;long time = 10000;while (count <= 8) {date.setTime(time);System.out.println(date.toString());count++;time *= 10;}}}9.4public class Exercise09_04 {public static void main(String[] args) {Random random = new Random(1000);for (int i = 0; i < 50; i++)System.out.print(random.nextInt(100) + " ");}9.5public class Exercise09_05 {public static void main(String[] args) {GregorianCalendar calendar = new GregorianCalendar();System.out.println("Year is " + calendar.get(GregorianCalendar.YEAR)); System.out.println("Month is " + calendar.get(GregorianCalendar.MONTH)); System.out.println("Date is " + calendar.get(GregorianCalendar.DATE));calendar.setTimeInMillis(1234567898765L);System.out.println("Year is " + calendar.get(GregorianCalendar.YEAR)); System.out.println("Month is " + calendar.get(GregorianCalendar.MONTH)); System.out.println("Date is " + calendar.get(GregorianCalendar.DATE)); }}9.6public class Exercise09_06 {static String output = "";/** Main method */public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter yearSystem.out.print("Enter full year (i.e. 2001): ");int year = input.nextInt();// Prompt the user to enter monthSystem.out.print("Enter month in number between 1 and 12: ");int month = input.nextInt();// Print calendar for the month of the yearprintMonth(year, month);System.out.println(output);}/** Print the calendar for a month in a year */static void printMonth(int year, int month) {// Get start day of the week for the first date in the monthint startDay = getStartDay(year, month);// Get number of days in the monthint numOfDaysInMonth = getNumOfDaysInMonth(year, month);// Print headingsprintMonthTitle(year, month);// Print bodyprintMonthBody(startDay, numOfDaysInMonth);}/** Get the start day of the first day in a month */static int getStartDay(int year, int month) {// Get total number of days since 1/1/1800int startDay1800 = 3;long totalNumOfDays = getTotalNumOfDays(year, month);// Return the start dayreturn (int)((totalNumOfDays + startDay1800) % 7);}/** Get the total number of days since Jan 1, 1800 */static long getTotalNumOfDays(int year, int month) {long total = 0;// Get the total days from 1800 to year -1for (int i = 1800; i < year; i++)if (isLeapYear(i))total = total + 366;elsetotal = total + 365;// Add days from Jan to the month prior to the calendar month for (int i = 1; i < month; i++)total = total + getNumOfDaysInMonth(year, i);return total;}/** Get the number of days in a month */static int getNumOfDaysInMonth(int year, int month) {if (month == 1 || month==3 || month == 5 || month == 7 ||month == 8 || month == 10 || month == 12)return 31;if (month == 4 || month == 6 || month == 9 || month == 11)return 30;if (month == 2)if (isLeapYear(year))return 29;elsereturn 28;return 0; // If month is incorrect.}/** Determine if it is a leap year */static boolean isLeapYear(int year) {if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) return true;return false;}/** Print month body */static void printMonthBody(int startDay, int numOfDaysInMonth) { // Pad space before the first day of the monthint i = 0;for (i = 0; i < startDay; i++)output += " ";for (i = 1; i <= numOfDaysInMonth; i++) {if (i < 10)output += " " + i;elseoutput += " " + i;if ((i + startDay) % 7 == 0)output += "\n";}output += "\n";}/** Print the month title, i.e. May, 1999 */static void printMonthTitle(int year, int month) {output += " " + getMonthName(month)+ ", " + year + "\n";output += "-----------------------------\n";output += " Sun Mon Tue Wed Thu Fri Sat\n";}/** Get the English name for the month */static String getMonthName(int month) {String monthName = null;switch (month) {case 1: monthName = "January"; break;case 2: monthName = "February"; break;case 3: monthName = "March"; break;case 4: monthName = "April"; break;case 5: monthName = "May"; break;case 6: monthName = "June"; break;case 7: monthName = "July"; break;case 8: monthName = "August"; break;case 9: monthName = "September"; break;case 10: monthName = "October"; break;case 11: monthName = "November"; break;case 12: monthName = "December";}return monthName;}}9.7public class Exercise09_07 {public static void main (String[] args) {Account account = new Account(1122, 20000);Account.setAnnualInterestRate(4.5);account.withdraw(2500);account.deposit(3000);System.out.println("Balance is " + account.getBalance()); System.out.println("Monthly interest is " +account.getMonthlyInterest());System.out.println("This account was created at " +account.getDateCreated());}}class Account {private int id;private double balance;private static double annualInterestRate;private java.util.Date dateCreated;public Account() {dateCreated = new java.util.Date();}public Account(int newId, double newBalance) {id = newId;balance = newBalance;dateCreated = new java.util.Date();}public int getId() {return this.id;}public double getBalance() {return balance;}public static double getAnnualInterestRate() {return annualInterestRate;}public void setId(int newId) {id = newId;}public void setBalance(double newBalance) {balance = newBalance;}public static void setAnnualInterestRate(double newAnnualInterestRate) { annualInterestRate = newAnnualInterestRate;}public double getMonthlyInterest() {return balance * (annualInterestRate / 1200);}public java.util.Date getDateCreated() { return dateCreated;}public void withdraw(double amount) {balance -= amount;}public void deposit(double amount) {balance += amount;}}9.8public class Exercise09_08 {public static void main(String[] args) { Fan1 fan1 = new Fan1();fan1.setSpeed(Fan1.FAST);fan1.setRadius(10);fan1.setColor("yellow");fan1.setOn(true);System.out.println(fan1.toString());Fan1 fan2 = new Fan1();fan2.setSpeed(Fan1.MEDIUM);fan2.setRadius(5);fan2.setColor("blue");fan2.setOn(false);System.out.println(fan2.toString()); }}class Fan1 {public static int SLOW = 1;public static int MEDIUM = 2;public static int FAST = 3;private int speed = SLOW;private boolean on = false;private double radius = 5;private String color = "white";public Fan1() {}public int getSpeed() {return speed;}public void setSpeed(int newSpeed) {speed = newSpeed;}public boolean isOn() {return on;}public void setOn(boolean trueOrFalse) {this.on = trueOrFalse;}public double getRadius() {return radius;}public void setRadius(double newRadius) { radius = newRadius;}public String getColor() {return color;}public void setColor(String newColor) {color = newColor;}@Overridepublic String toString() {return"speed " + speed + "\n"+ "color " + color + "\n"+ "radius " + radius + "\n"+ ((on) ? "fan is on" : " fan is off"); }}public class Exercise09_09 {public static void main(String[] args) {RegularPolygon polygon1 = new RegularPolygon();RegularPolygon polygon2 = new RegularPolygon(6, 4);RegularPolygon polygon3 = new RegularPolygon(10, 4, 5.6, 7.8);System.out.println("Polygon 1 perimeter: " +polygon1.getPerimeter());System.out.println("Polygon 1 area: " + polygon1.getArea());System.out.println("Polygon 2 perimeter: " +polygon2.getPerimeter());System.out.println("Polygon 2 area: " + polygon2.getArea());System.out.println("Polygon 3 perimeter: " +polygon3.getPerimeter());System.out.println("Polygon 3 area: " + polygon3.getArea());}}class RegularPolygon {private int n = 3;private double side = 1;private double x;private double y;public RegularPolygon() {}public RegularPolygon(int number, double newSide) {n = number;side = newSide;}public RegularPolygon(int number, double newSide, double newX, double newY) {n = number;side = newSide;x = newX;y = newY;}public int getN() {return n;}public void setN(int number) {n = number;}public double getSide() {return side;}public void setSide(double newSide) {side = newSide;}public double getX() {return x;}public void setX(double newX) {x = newX;}public double getY() {return y;}public void setY(double newY) {y = newY;}public double getPerimeter() {return n * side;}public double getArea() {return n * side * side / (Math.tan(Math.PI / n) * 4); }}9.10public class Exercise09_10 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a, b, c: ");double a = input.nextDouble();double b = input.nextDouble();double c = input.nextDouble();QuadraticEquation equation = new QuadraticEquation(a, b, c);double discriminant = equation.getDiscriminant();if (discriminant < 0) {System.out.println("The equation has no roots");}else if (discriminant == 0){System.out.println("The root is " + equation.getRoot1());}else// (discriminant >= 0){System.out.println("The roots are " + equation.getRoot1()+ " and " + equation.getRoot2());}}}class QuadraticEquation {private double a;private double b;private double c;public QuadraticEquation(double newA, double newB, double newC) {a = newA;b = newB;c = newC;}double getA() {return a;}double getB() {return b;}double getC() {return c;}double getDiscriminant() {return b * b - 4 * a * c;}double getRoot1() {if (getDiscriminant() < 0)return 0;else {return (-b + getDiscriminant()) / (2 * a);}}double getRoot2() {if (getDiscriminant() < 0)return 0;else {return (-b - getDiscriminant()) / (2 * a);}}}9.11public class Exercise09_11 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a, b, c, d, e, f: ");double a = input.nextDouble();double b = input.nextDouble();double c = input.nextDouble();double d = input.nextDouble();double e = input.nextDouble();double f = input.nextDouble();LinearEquation equation = new LinearEquation(a, b, c, d, e, f);if (equation.isSolvable()) {System.out.println("x is " +equation.getX() + " and y is " + equation.getY());}else {System.out.println("The equation has no solution");}}}class LinearEquation {private double a;private double b;private double c;private double d;private double e;private double f;public LinearEquation(double newA, double newB, double newC, double newD, double newE, double newF) {a = newA;b = newB;c = newC;d = newD;e = newE;f = newF;}double getA() {return a;}double getB() {return b;}double getC() {return c;}double getD() {return d;}double getE() {return e;}double getF() {return f;}boolean isSolvable() {return a * d - b * c != 0;}double getX() {double x = (e * d - b * f) / (a * d - b * c);return x;}double getY() {double y = (a * f - e * c) / (a * d - b * c);return y;}}9.12public class Exercise09_12 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter the endpoints of the first line segment: ");double x1 = input.nextDouble();double y1 = input.nextDouble();double x2 = input.nextDouble();double y2 = input.nextDouble();System.out.print("Enter the endpoints of the second line segment: ");double x3 = input.nextDouble();double y3 = input.nextDouble();double x4 = input.nextDouble();double y4 = input.nextDouble();// Build a 2 by 2 linear equationdouble a = (y1 - y2);double b = (-x1 + x2);double c = (y3 - y4);double d = (-x3 + x4);double e = -y1 * (x1 - x2) + (y1 - y2) * x1;double f = -y3 * (x3 - x4) + (y3 - y4) * x3;LinearEquation equation = new LinearEquation(a, b, c, d, e, f);if (equation.isSolvable()) {System.out.println("The intersecting point is: (" +equation.getX() + ", " + equation.getY() + ")");}else {System.out.println("The two lines do not cross ");}}}9.13public class Exercise09_13 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter the number of rows and columns of the array: ");int numberOfRows = input.nextInt();int numberOfColumns = input.nextInt();double[][] a = new double[numberOfRows][numberOfColumns];System.out.println("Enter the array: ");for (int i = 0; i < a.length; i++)for (int j = 0; j < a[i].length; j++)a[i][j] = input.nextDouble();Location location = locateLargest(a);System.out.println("The location of the largest element is " + location.maxValue + " at ("+ location.row + ", " + location.column + ")");}public static Location locateLargest(double[][] a) {Location location = new Location();location.maxValue = a[0][0];for (int i = 0; i < a.length; i++)for (int j = 0; j < a[i].length; j++) {if (location.maxValue < a[i][j]) {location.maxValue = a[i][j];location.row = i;location.column = j;}}return location;}}class Location {int row, column;double maxValue;}9.14public class Exercise09_14 {public static void main(String[] args) {int size = 100000;double[] list = new double[size];for (int i = 0; i < list.length; i++) {list[i] = Math.random() * list.length;}StopWatch stopWatch = new StopWatch();selectionSort(list);stopWatch.stop();System.out.println("The sort time is " + stopWatch.getElapsedTime()); }/** The method for sorting the numbers */public static void selectionSort(double[] list) {for (int i = 0; i < list.length - 1; i++) {// Find the minimum in the list[i..list.length-1]double currentMin = list[i];int currentMinIndex = i;for (int j = i + 1; j < list.length; j++) {if (currentMin > list[j]) {currentMin = list[j];currentMinIndex = j;}}// Swap list[i] with list[currentMinIndex] if necessary;if (currentMinIndex != i) {list[currentMinIndex] = list[i];list[i] = currentMin;}}}}class StopWatch {private long startTime = System.currentTimeMillis(); private long endTime = startTime;public StopWatch() {}public void start() {startTime = System.currentTimeMillis();}public void stop() {endTime = System.currentTimeMillis();}public long getElapsedTime() {return endTime - startTime;}}。

Python语言程序设计美梁勇第5章习题解答

Python语言程序设计美梁勇第5章习题解答

Python语言程序设计美梁勇第5章习题解答第5章习题解答一、选择题1. 在Python中,下列哪个不是有效的变量名?A. 1nameB. Name1C. _nameD. name_1正确答案:A. 1name2. 下列哪个运算符不是Python的算术运算符?A. +B. *C. /D. %正确答案:D. %3. 在Python中,下列哪个是赋值运算符?A. ==B. >C. +=D. and正确答案:C. +=4. 下列关于列表的描述中,哪个是错误的?A. 列表是一种有序的集合B. 列表可以包含不同的数据类型C. 列表的索引是从0开始的D. 列表可以通过下标修改其中的元素正确答案:B. 列表可以包含不同的数据类型5. 下列关于字典的描述中,哪个是正确的?A. 字典是一种有序的集合B. 字典的每个元素都有一个对应的键和值C. 字典的元素可以通过索引来访问D. 字典中的键必须是字符串类型正确答案:B. 字典的每个元素都有一个对应的键和值二、编程题1. 编写一个函数,接受一个字符串作为参数,返回该字符串的长度。

```pythondef calculate_length(string):return len(string)```2. 编写一个程序,要求用户输入两个数字,并计算它们的和、差、积和商,最后将结果输出。

```pythonnum1 = float(input("请输入第一个数字:"))num2 = float(input("请输入第二个数字:"))add = num1 + num2subtract = num1 - num2multiply = num1 * num2divide = num1 / num2print("两个数字的和:", add)print("两个数字的差:", subtract)print("两个数字的积:", multiply)print("两个数字的商:", divide)```3. 定义一个列表,其中包含5个学生的成绩,计算并输出这5个学生的平均成绩。

《Java语言程序设计-基础篇》答案-第05章

《Java语言程序设计-基础篇》答案-第05章

第5章 数组复习题5.1 答:(略)5.2 答:使用数组名和下标。

如:arrayName[index]5.3 答:声明数组时不为数组分配内存,使用new 运算符为数组分配内存。

输出结果: x is 60The size of numbers is 305.4 答:依次为:对、错、对、错5.5 答:有效的数组名分别是:d, f, r5.6 答:整数,05.7 答:a[2]5.8 答:出现下标越界错误,具体是:ArrayIndexOutOfBoundsException。

5.9 答:第3行改为:double[] r = new double[100]; 第5行的r.length()改为:r.length 第6行的r(i)改为:r[i]5.10 答:语句如下:int[] t = new int[source.length];System.arraycopy(source, 0, t, 0, source.length);5.11 答:不是修改数组大小,而创建一个新数组,并用myList 去引用。

5.12 答:不正确。

是将数组地址传递给方法形参。

5.13 答:输出如下:numbers is 0 and numbers[0] is 35.14 答:数组存放在堆(heap)中。

第2问参见P144图5-7。

5.15 - 5.18 (略)5.19 答:int[] matrix = new int[4][5];课后答案网ww w.kh da w .c om5.20 答:可以。

5.21 答:输出:array[0][1] is 2课后答案网ww w.kh da w .c om。

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

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

System.out.println("Programming is fun .");
}
}
1.2 public class Test{
public static void main(String[] args){
for(int i = 0;i <= 4;i++){
System.out.println("Welcome to Java !");
public static void main(String[] args){ double S = 14 / 1.6;
double T = 45 * 60 + 30; double speed = S / T; System.out.println(speed); } } 1.11 public class Test{ public static void main(String[] args){ int BN = 312032486; //original person numbers double EveryYS,EveryYBP,EveryYDP,EveryYMP; EveryYS = 365 * 24 * 60 * 60; EveryYBP = EveryYS / 7; EveryYDP = EveryYS / 13; EveryYMP = EveryYS / 45; int FirstYP,SecondYP,ThirdYP,FourthYP,FivthYP; FirstYP = (int)(BN + EveryYBP + EveryYMP - EveryYDP); SecondYP = (int)(FirstYP + EveryYBP + EveryYMP - EveryYDP); ThirdYP = (int)(SecondYP + EveryYBP + EveryYMP - EveryYDP); FourthYP = (int)(ThirdYP + EveryYBP + EveryYMP - EveryYDP); FivthYP = (int)(FourthYP + EveryYBP + EveryYMP - EveryYDP); System.out.println(FirstYP); System.out.println(SecondYP); System.out.println(ThirdYP); System.out.println(FourthYP); System.out.println(FivthYP); } } 1.12 public class Test{ public static void main(String[] args){ double S = 24 * 1.6; double T = (1 * 60 + 40) * 60 + 35; double speed = S / T; System.out.println(speed); } } 1.13 import java.util.Scanner; public class Test{ public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.println("input a,b,c,d,e,f value please:"); double a = input.nextDouble(); double b = input.nextDouble(); double c = input.nextDouble(); double d = input.nextDouble(); double e = input.nextDouble();

《Java程序设计》教材第五章练习题答案

《Java程序设计》教材第五章练习题答案

习题一、选择题1. 面向对象程序设计的基本特征是(BCD)。

(多选)A.抽象B.封装C.继承D.多态2.下面关于类的说法正确的是(ACD)。

(多选)A.类是Java 语言中的一种复合数据类型。

B.类中包含数据变量和方法。

C.类是对所有具有一定共性的对象的抽象。

D.Java 语言的类只支持单继承。

上机指导1.设计银行项目中的注册银行用户基本信息的类,包括账户卡号、姓名、身份证号、联系电话、家庭住址。

要求是一个标准Java类(数据私有,提供seter/getter),然后提供一个toString方法打印该银行用户的信息。

答:源代码请参见“CH05_LAB\src\com\inspur\ch05\BankUser.java”2.设计银行项目中的帐户信息,包括帐户卡号、密码、存款,要求如“练习题1”。

答:源代码请参见“CH05_LAB\src\com\inspur\ch05\Account.java”3.设计银行项目中的管理员类,包括用户名和密码。

要求如“练习题1”。

答:源代码请参见“CH05_LAB\src\com\inspur\ch05\Manager.java”4.创建一个Rectangle类。

添加两个属性width、height,分别表示宽度和高度,添加计算矩形的周长和面积的方法。

测试输出一个矩形的周长和面积。

答:源代码请参见“CH05_LAB\src\com\inspur\ch05\Rectangle.java”5.猜数字游戏:一个类A有一个成员变量v,有一个初值100。

定义一个类,对A类的成员变量v进行猜。

如果大了则提示大了,小了则提示小了。

等于则提示猜测成功。

答:源代码请参见“CH05_LAB\src\com\inspur\ch05\Guess.java”6.编写一个Java程序,模拟一个简单的计算器。

定义名为Computer的类,其中两个整型数据成员num1和num1,编写构造方法,赋予num1和num2初始值,再为该类定义加、减、乘、除等公有方法,分别对两个成员变量执行加减乘除的运算。

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

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

j a v a语言程序设计基础篇第十版练习答案精编Document number:WTT-LKK-GBB-08921-EIGG-2298601import class Exercise14_01 extendsApplication {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}02import class Exercise14_02 extends Application {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}03import class Exercise14_03 extends Application {@Override One is to use the hint in the book.ArrayList<Integer> list = new ArrayList<>(); for (int i = 1; i <= 52; i++) {(i);}HBox pane = new HBox(5);;().add(new ImageView("image/card/" + (0) +".png"));().add(new ImageView("image/card/" + (1) +".png"));().add(new ImageView("image/card/" + (2) +".png"));Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}04import class Exercise14_04 extends Application {@Override dd(txt);}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}05import class Exercise14_05 extends Application {@Override dd(txt);}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}05import class Exercise14_05 extends Application {@Override dd(txt);}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}06import class Exercise14_06 extends Application {@Override dd(rectangle);}}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}07import class Exercise14_07 extends Application {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}08import class Exercise14_08 extends Application {@Override ng"), j, i);}}Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}09import class Exercise14_09 extends Application {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}class FanPane extends Pane {double radius = 50;public FanPane() {Circle circle = new Circle(60, 60, radius);;;getChildren().add(circle);Arc arc1 = new Arc(60, 60, 40, 40, 30, 35);; ddAll(arc1, arc2, arc3, arc4);}}10import class Exercise14_10 extends Application {@Override ddAll, ;Arc arc2 = new Arc(100, 140, 50, 20, 180, 180); ;;().addAll(ellipse, arc1, arc2,new Line(50, 40, 50, 140), new Line(150, 40, 150, 140));Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}11import class Exercise14_11 extends Application {@Override ddAll(circle, ellipse1, ellipse2,circle1, circle2, line1, line2, line3, arc);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}12import class Exercise14_12 extends Application {@Override ddAll(r1, text1, r2, text2, r3, text3, r4, text4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}13import class Exercise14_13 extends Application {@Override ddAll(arc1, text1, arc2, text2, arc3, text3, arc4, text4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}14import class Exercise14_14 extends Application {@Override ddAll(r1, r2, line1, line2, line3, line4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}15import class Exercise14_15 extends Application {@Override ddAll(polygon, text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16import class Exercise14_16 extends Application {@Override ind().divide(3));().bind());().bind().divide(3));;Line line2 = new Line(0, 0, 0, 0);().bind().multiply(2).divide(3));().bind());().bind().multiply(2).divide(3));;Line line3 = new Line(0, 0, 0, 0);().bind().divide(3));().bind().divide(3));().bind());;Line line4 = new Line(0, 0, 0, 0);().bind().multiply(2).divide(3));().bind().multiply(2).divide(3));().bind());;().addAll(line1, line2, line3, line4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}17import class Exercise14_17 extends Application {@Override ddAll(arc, line1, line2, line3, circle, line4, line5, line6, line7, line8);Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}18import class Exercise14_18 extends Application {@Override ddAll(polyline, line1, line2,line3, line4, line5, line6, text1, text2);Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}19import class Exercise14_19 extends Application {@Override ddAll(polyline1, polyline2, line1,line2,line3, line4, line5, line6, text1, text2,text3,text4, text5, text6, text7);Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}20import class Exercise14_20 extends Application {@Override dd(new Line(x1, y1, x2, y2));dd(new Line(x2, y2, (x2 + (arctan + set45) * arrlen)),((y2)) + (arctan + set45) * arrlen)));().add(new Line(x2, y2, (x2 + (arctan - set45) * arrlen)),((y2)) + (arctan - set45) * arrlen)));}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}21import class Exercise14_21 extends Application {@Override istance(x2, y2) + "");().addAll(circle1, circle2, line, text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}22import class Exercise14_22 extends Application {@Override ddAll(circle1, circle2, line, text1, text2);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}23import class Exercise14_23 extends Application {@Override ddAll(r1, r2, text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}24import class Exercise14_24 extends Application {@Override ddAll(polygon, new Circle(x5, y5, 10), text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}25import class Exercise14_25 extends Application {@Override ddAll(circle, polygon);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}26import class Exercise14_26 extends Application {@Override ddAll(clock1, clock2);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}27import class Exercise14_27 extends Application {@OverrideNot needed for running from the command line. */public static void main(String[] args) {launch(args);}}class DetailedClockPane extends Pane {private int hour;private int minute;private int second;lear();getChildren().addAll(circle, sLine, mLine, hLine);dd(new Line(xOuter, yOuter, xInner, yInner));}dd(text);}}}28import class Exercise14_28 extends Application {@OverrideNot needed for running from the command line.*/public static void main(String[] args) {launch(args);}}class ClockPaneWithBooleanProperties extends Pane { private int hour;private int minute;private int second;private boolean hourHandVisible = true;private boolean minuteHandVisible = true; private boolean secondHandVisible = true;public boolean isHourHandVisible() {return hourHandVisible;}public void setHourHandVisible(boolean hourHandVisible) {= hourHandVisible;paintClock();}public boolean isMinuteHandVisible() {return minuteHandVisible;}public void setMinuteHandVisible(boolean minuteHandVisible) {= minuteHandVisible;paintClock();}public boolean isSecondHandVisible() {return secondHandVisible;public void setSecondHandVisible(boolean secondHandVisible) {= secondHandVisible;paintClock();}lear();getChildren().addAll(circle, t1, t2, t3, t4);if (secondHandVisible) {getChildren().add(sLine);}if (minuteHandVisible) {getChildren().add(mLine);}if (hourHandVisible) {getChildren().add(hLine);}}}import class Exercise14_29 extends Application {final static double HGAP = 20;final static double VGAP = 20;final static double RADIUS = 5;final static double LENGTH_OF_SLOTS = 40;final static double LENGTH_OF_OPENNING = 15;final static double Y_FOR_FIRST_NAIL = 50;final static double NUMBER_OF_SLOTS = 9;final static double NUMBER_OF_ROWS =NUMBER_OF_SLOTS - 2;@Override dd(c);}}dd(new Line(x, y, x, y + LENGTH_OF_SLOTS)); }dd(new Line(centerX - (NUMBER_OF_ROWS - 1) * HGAP / 2 - HGAP,y + LENGTH_OF_SLOTS, centerX -(NUMBER_OF_ROWS - 1) * HGAP / 2 + NUMBER_OF_ROWS * HGAP,y + LENGTH_OF_SLOTS));dd(new Line(centerX + HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX - (NUMBER_OF_ROWS - 1) * HGAP / 2 + NUMBER_OF_ROWS * HGAP, y));().add(new Line(centerX - HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX - (NUMBER_OF_ROWS - 1) * HGAP / 2 - HGAP, y));dd(new Line(centerX - HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX - HGAP / 2, Y_FOR_FIRST_NAIL - LENGTH_OF_OPENNING));().add(new Line(centerX + HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX + HGAP / 2, Y_FOR_FIRST_NAIL - LENGTH_OF_OPENNING));Not needed for running from the command line.*/public static void main(String[] args) { launch(args);}}。

《Java语言程序设计:基础篇》课后复习题答案-第五章

《Java语言程序设计:基础篇》课后复习题答案-第五章

Chapter5Methods1.At least three benefits:(1)Reuse code;(2)Reduce complexity;(3)Easy to maintain.See the Sections5.2and5.3on how to declare and invoke methods.What is thesubtle difference between“defining a method”and“declaring a variable”?A declaration usually involvesallocating memory to store a variable,but a definitiondoesn’t.2.void3.Yes.return(num1>num2)?num1:num2;4.True:a call to a method with a void return type is always a statement itself.False:a call to a value-returning method is always a component of an expression.5.A syntax error occurs if a return statement is not used to return a value in a value-returning method.You can have a return statement in a void method,whichsimply exits the method.But a return statement cannot return a value such asreturn x+y in a void method.6.See Section5.2.puting a sales commission given the sales amount and the commission ratepublic static double getCommission(double salesAmount,doublecommissionRate)Printing a calendar for a monthpublic static void printCalendar(int month,int year)Computing a square rootpublic static double sqrt(double value)Testing whether a number is even and return true if it ispublic static boolean isEven(int value)Printing a message for a specified number of timespublic static void printMessage(String message,int times)Computing the monthly payment,given the loan amount,number of years,and annual interest rate.public static double monthlyPayment(double loan,intnumberOfYears,double annualInterestRate)Finding the corresponding uppercase letter given a lowercase letter.public static char getUpperCase(char letter)8.Line2:method1is not defined correctly.It does not have a return type or void.Line2:type int should be declared for parameter m.Line7:parameter type for n should be double to match method2(3.4).Line11:if(n<0)should be removed in method,otherwise a compile error is reported.9.public class Test{public static double xMethod(double i,double j){ while(i<j){j--;}return j;}}10.You pass actual parameters by passing the right type of value in the right order.The actual parameter can have the same name as its formal parameter.11."Pass by value"is to pass a copy of the value to the method.(A)The output of the program is0,because the variable max is not changed byinvoking the method max.(B)224248248162481632248163264(C)Before the call,variable times is3n=3Welcome to Java!n=2Welcome to Java!n=1Welcome to Java!After the call,variable times is3(D)12121421i is 512.Just before max is invoked.Space required for the main methodmax: 0Just entering max.Space required for the max methodmax: 0value2: 2 value1: 1Just before max is returnedSpace required for the main methodmax: 0Space required for the max methodmax: 2value2: 2 value1: 1 Space required for the main methodmax: 0Space required for the main methodmax: 0Right after max is returned13.Two methods with the same name,defined in the same class,is called method overloading.It is fine to have same method name,but different parameter types.You cannot overload methods based on return type,or modifiers.14.Methods public static void method(int x)and public static int method(int y)have the same signature method(int).15.Line 7:int n =1is wrong since n is already declared in the method signature.16.True17.(a)34+(int)(Math.random()*(55–34))(b)(int)(Math.random()*1000)(c)5.5+(Math.random()*(55.5–5.5))(d)(char)(‘a’+(Math.random()*(‘z’–‘a’+1))18.Math.sqrt(4)= 2.0Math.sin(2*Math.PI)=0Math.cos(2*Math.PI)=1Math.pow(2,2)= 4.0Math.log(Math.E)=1Math.exp(1)= 2.718Math.max(2,Math.min(3,4))=3 Math.rint(-2.5)=-2.0Math.ceil(-2.5)=-2.0Math.floor(-2.5)=-3.0Math.round(-2.5f)=-2Math.round(-2.5)=-2Math.rint(2.5)= 2.0Math.ceil(2.5)= 3.0Math.floor(2.5)= 2.0Math.round(2.5f)=3Math.round(-2.5)=-2Math.round(Math.abs(-2.5))=3。

Java课后题-第5章答案

Java课后题-第5章答案

一.程序设计题1.定义一个汽车类Car,要求如下:1)属性包括:汽车品牌brand(String类型)、颜色color(String类型)和速度speed(double类型),并且所有属性为私有。

2)至少提供一个有参的构造方法(要求品牌和颜色可以初始化为任意值,但速度的初始值必须为0)。

3)为私有属性提供访问器方法。

注意:汽车品牌一旦初始化之后不能修改。

定义测试类CarTest,在其main方法中创建一个品牌为“benz”、颜色为“black”的汽车。

public class Car{private String brand;private String color;private double speed;public Car(String brand,String color){this.brand=brand;this.color=color;}public String getColor(){return color;}public void setColor(String color){this.color=color;}public double getSpeed(){return speed;}public void setSpeed(double speed){this.speed=speed;}public String getBrand(){return brand;}}public class CarTest{public static void main(String[]args){Car c1=new Car("benz","black");}}2.定义一个图书类Book,要求如下:1)属性包括:书名name(String类型)、作者author(String类型),单价price(double类型),数量amount(int类型),并且所有属性为私有。

java答案第五章

java答案第五章
SetPi b=new SetPi(3.00);
"改变Pi=3.00圆的面积:"+c.area());
}
}
运行结果:
3.在什么情况下,可以对父类对象的引用进行强制类型转换,使其转化成子类对象的引用?
答:一个对象被塑型为父类或接口后,可以再一次被塑型回到它原来所属的类,即转化成原类对象的引用。
4.声明一个接口,此接口至少具有一个方法;在一个方法中声明内部类实现此接口,并返回此接口的引用。
public class Circle implements Shape2D{
double radius;
public Circle(double r){radius=r;}
public double area(){return Pi*radius*radius;}
}
//A类(测试接口中隐含final的area()方法)
this.id=newid;
}
public void setname(String newname){
=newname;
}
public void setscoreOfenglish(float newscoreOfenglish){
this.scoreOfenglish=newscoreOfenglish;
//Student类
public class Student{
String id;
String name;
float scoreOfenglish;
float scoreOfmath;
float scoreOfcomputer;
float scoreOfsum;
//构造方法
public Student(){

java语言程序设计基础篇第十版第五章

java语言程序设计基础篇第十版第五章

java语言程序设计基础篇第十版第五章摘要:一、Java 语言程序设计基础篇第十版第五章概述二、Java 程序设计基本概念与技术三、面向对象程序设计四、Java 程序设计高级主题五、Java 语言程序设计基础篇第十版第五章知识点详解六、Java 语言程序设计基础篇第十版第五章课后答案与练习题正文:一、Java 语言程序设计基础篇第十版第五章概述本章节主要介绍了Java 语言程序设计的基础知识,包括基本程序设计、语言结构、面向对象程序设计、继承与多态等内容。

通过学习本章节,读者可以掌握Java 语言的基本语法和编程技巧,为后续的学习打下坚实的基础。

二、Java 程序设计基本概念与技术1.基本数据类型:Java 语言中常用的基本数据类型包括整型、浮点型、布尔型和字符型等。

2.控制结构:Java 语言中的控制结构包括条件语句(如if-else)、循环语句(如for、while 和do-while)以及分支语句(如switch)等。

3.函数与方法:Java 语言中的函数称为方法,它可以实现代码的封装和重用。

方法的调用方式包括直接调用、间接调用和链式调用等。

4.数组:Java 语言中的数组是一种用于存储多个相同类型数据的集合。

数组可以进行遍历、排序等操作。

5.面向对象程序设计:Java 语言是一种面向对象的编程语言,它支持类和对象的概念。

类是一种抽象的数据类型,包含属性和方法;对象是类的实例,通过创建对象,可以调用类中定义的方法来实现具体的功能。

三、面向对象程序设计1.类与对象:Java 语言中的面向对象程序设计主要通过类和对象来实现。

类是一种抽象的数据类型,包含属性和方法;对象是类的实例,通过创建对象,可以调用类中定义的方法来实现具体的功能。

2.继承与多态:继承是Java 语言中实现代码重用的一种方式,它允许一个类(子类)继承另一个类(父类)的属性和方法。

多态是Java 语言中实现面向对象程序设计的重要特性之一,它允许一个接口或抽象类有多种实现方式。

JAVA语言程序设计(基础篇)答案

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程序设计第五章课后答案

解析JAVA程序设计第五章课后答案

第5章习题解答1.流的主要特征有哪些,用流来实现JAVA中的输入输出有什么优点?答: 一是单向性,即数据只能从数据源流向数据宿;二是顺序性,先从数据源流出的数据一定比后流出的数据先到达数据宿;三是数据流必须而且只能和一个数据源与一个数据宿相连。

优点是体现了面向对象程序设计的概念,通过流可以把对不同类型的输入/输出设备的操作统一为用流来实现。

2.对字节流和字符流进行读写操作的一般步骤是什么?答:声明流对象,创建流对象,通过流对象进行读(写)操作,关闭流对象。

3. 有哪些常用的字节流和字符流,他们的主要区别是什么?答: InputStream/OutputStrem:普通字节流,所有字节流的基类。

FileInputStream/ FileOutputStream:用于从文件中读写数据。

BufferedInputStream/ BufferedOutputStream:用于从缓冲区输入流中读写数据。

采用缓冲区流可减少实际上从外部输入设备上读写数据的次数,从而提高效率。

DataInputStream/ DataOutputStream:按读写数据对象的大小从字节流中读写数据,而不是象其它字节流那样以字节为基本单位。

PipedInputStream/ PipedOutputStream:管道输流用于从另一个线程中读写数据。

4.么是异常?说明Java中的异常处理机制?试述JAVA中异常的抛出和传递过程?答: 异常是程序设计语言提供的一种机制,它用于在程序运行中的非常规情况下,控制程序对非常规情况进合理的处理。

Java提供了try-catch-finally语句来对异常进行处理。

先按照正常顺序执行try子句中的语句,若在执行过程中出现异常,则try子句中还未被执行的语句将再也不会被执行。

而程序控制立即转移到catch子句,将发生的异常与catch子句中的异常进行匹配,若找到一个匹配,就执行该catch子句中的语句。

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

Java语言程序设计(基础篇)(第10版 梁勇著)第二章练习题答案
第二章基本程序设计练习题答案本人在自学编程过程中发现本书答案很难找找到的要么不完整要么错误百出所以我将自己所做的练习题答案提供给有需要者供大家交流
《Java语言程序设计(基础篇)》(第10版 梁勇 著) 第二章 基本程序设计 练习题答案
本人在自学编程过程中,发现本书答案很难找,找到的要么不完整、要么错误百出,所以我将自己所做的 练习题答案,提供给有需要者,供大家交流。本章答案均为本人一字一字所敲,答案均经过验证,虽为初学者, 但代码均按照书中规范要求书写,如有错误或更好的建议,请指正交流。
// 第二章 P59 练习题2.1 (将摄氏温度转为华氏温度) import java.util.Scanner;
public class CelsiusToFahrenheit {
public static void main(String[] args) { // 华氏温度和摄氏温度的转换公式为:华氏温度 = (9/5)*摄氏温度+32 Scanner input = new Scanner(System.in);
System.out.print("Enter the time zone offset to GMT: "); long timeZoneOffset = input.nextLong(); // 此处用long还是int?
long totalMilliseconds = System.currentTimeMillis(); long totalSeconds = totalMilliseconds / 1000; long currentSecond = totalSeconds % 60; long totalMinutes = totalSeconds / 60; long currentMinute = totalMinutes % 60; long totalHours = totalMinutes / 60; long currentHour = totalHours % 24; long hour = currentHour + timeZoneOffset;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Map接口用于存储键值对。

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

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

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

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

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

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

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

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

JAVA语言程序设计基础课后习题第五章

JAVA语言程序设计基础课后习题第五章

JAVA语⾔程序设计基础课后习题第五章//exercise 5.1package fivechapterexercise1;public class first {public static void main(String[] args) {// TODO Auto-generated method stubfinal int NUMBER_OF_PENTAGONAL_PER_LINE=10;for(int i=1;i<=100;i++){System.out.print(getpentagonalnumber(i)+" ");if(i%NUMBER_OF_PENTAGONAL_PER_LINE==0)System.out.println();}}public static int getpentagonalnumber(int i){return i*(3*i-1)/2;}}//exercise 5.2package fivechapterexercise1;import java.util.Scanner;public class second {public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);System.out.print("input a integer :");int integer=in.nextInt();System.out.println("The sum of digits is "+getsumdigits(integer));}public static int getsumdigits(int integer){int sum=0;while(integer!=0){sum += integer%10;integer /=10;}return sum;}}//exercise 5.3package fivechapterexercise1;import java.util.Scanner;public class third {public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);System.out.print("please input a integer:");int integer=in.nextInt();System.out.println("This integer is a palindrome?"+ispalindrome(integer));}public static boolean ispalindrome(int integer){if(integer==reverse(integer))return true;elsereturn false;}public static int reverse(int integer){int count=0;int temp=integer;while(integer!=0){integer /=10;count++;}int sum=0;for(int i=count;i>=1;i--){sum=sum+(int)(Math.pow(10, i-1))*(temp%10);temp /= 10;}return sum;}}//exercise 5.4package fivechapterexercise1;import java.util.Scanner;public class fourth {public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);System.out.print("please input integer:");int integer=in.nextInt();System.out.print("The palindrome is:"+reverse(integer));}public static int reverse(int integer){int count=0;int temp=integer;while(integer!=0){integer /=10;count++;}int sum=0;for(int i=count;i>=1;i--){sum=sum+(int)(Math.pow(10, i-1))*(temp%10);temp /= 10;}return sum;}}//exercise 5.5package fivechapterexercise1;public class fifth {public static void main(String[] args) {// TODO Auto-generated method stubdisplaySortedNumbers(4.4,2.4,9.8);}public static void displaySortedNumbers(double num1,double num2,double num3){if(num1>num2){double temp=num1;num1=num2;num2=temp;}if(num1>num3){double temp=num1;num1=num3;num3=temp;}if(num2>num3){double temp=num2;num2=num3;num3=temp;}System.out.println("Ascending order number three:"+num1+","+num2+","+num3+"."); }}//exercise 5.6package fivechapterexercise1;public class sixth {public static void main(String[] args) {// TODO Auto-generated method stubdisplayPattern(15);}public static void displayPattern(int n){for(int i=1;i<=n;i++){for(int j=i+1;j<=n;j++){System.out.print(" ");}for(int j=i;j>=1;j--){System.out.printf("%3d", j);}System.out.println();}}}//exercise 5.7package fivechapterexercise1;import java.util.Scanner;public class seventh {public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);System.out.print("input investment amount and annually interest rate:");int investmentAmount=in.nextInt();double annuallyInterestrate=in.nextDouble()/1200;System.out.println("Years\tFuture Value");for(int i=1;i<=30;i++){System.out.println(i+" \t"+futureInvestmentValue(investmentAmount,annuallyInterestrate,i));}}public static double futureInvestmentValue(double investmentAmount,double monthlyInterestRate,int years){double futureinvestmentValue=investmentAmount*(Math.pow((1+monthlyInterestRate),years));return futureinvestmentValue;}}//exercise 5.8package fivechapterexercise1;public class eighth {public static void main(String[] args) {// TODO Auto-generated method stubdouble celsius=40.0;double fahrenheit=120.0;System.out.println("摄⽒度\t华⽒度\t 华⽒度\t摄⽒度");for(int i=1;i<=10;i++){System.out.println(celsius+"\t"+((int)(celsiustofahrenheit(celsius)*10)/10.0)+"\t "+ fahrenheit+" "+((int)(fahrenheittocelsius(fahrenheit)*10)/10.0));celsius--;fahrenheit -=10;}}public static double celsiustofahrenheit(double celsius){return (9.0/5)*celsius+32;}public static double fahrenheittocelsius(double fahrenheit){return (fahrenheit-32)/(9.0/5);}}//exercise 5.9package fivechapterexercise1;public class ninth {public static void main(String[] args) {// TODO Auto-generated method stubdouble celsius=1.0;double fahrenheit=20.0;System.out.println("英尺\t⽶\t ⽶\t英尺");for(int i=1;i<=10;i++){System.out.println(celsius+"\t"+((int)(celsiustofahrenheit(celsius)*10)/10.0)+"\t "+ fahrenheit+" "+((int)(fahrenheittocelsius(fahrenheit)*10)/10.0));celsius++;fahrenheit +=5;}}public static double celsiustofahrenheit(double celsius){return celsius*0.305;}public static double fahrenheittocelsius(double fahrenheit){return (fahrenheit/0.305);}}//exercise 5.10package fivechapterexercise1;import fivechapter1.seventh;public class tenth {public static void main(String[] args) {// TODO Auto-generated method stubint count=0;for(int i=1;i<=10000;i++){if(seventh.isPrime(i))count++;}System.out.println("The number of prime is "+ count);}}//exercise 5.11package fivechapterexercise2;public class first {public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println("销售总额\t\t酬⾦");int salesamount=10000;for(int i=1;i<20;i++){System.out.println(salesamount+"\t\t"+computecommission(salesamount));salesamount+=5000;}}public static double computecommission(double salesamount){if(salesamount<5000)return salesamount*0.08;else if(salesamount<10000)return 5000*0.08+(salesamount-5000)*0.10;elsereturn 5000*0.08+5000*0.10+(salesamount-10000)*0.12;}}//exercise 5-12package fivechapterexercise2;public class second {public static void main(String[] args) {// TODO Auto-generated method stubprintChars('1','Z',10);}public static void printChars(char ch1,char ch2,int numberPerLine){int number=ch2-ch1+1;final int NUMBER_OF_CHARS_PER_LINE=numberPerLine;for(int i=0;i<number;i++){System.out.print((char)(ch1+i)+" ");if((i+1)%NUMBER_OF_CHARS_PER_LINE==0) System.out.println();}}}//exercise 5.13package fivechapterexercise2;public class third {public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println("i\t\tm(i)");for(int i=1;i<=20;i++){System.out.println(i+"\t\t"+m(i));}}public static double m(double integer){double sum=0;for(int i=1;i<=integer;i++){sum=sum+(double)i/(i+1);}return sum;}}//exercise 5-14package fivechapterexercise2;public class fourth {public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println("i\t\tm(i)");int number=10;for(int i=1;i<=10;i++){System.out.println(number+"\t\t"+m(number)); number +=10;}}public static double m(int integer){double sum=0;for(int i=1;i<=integer+1;i++){sum =sum+(Math.pow(-1,i-1)*(1.0/(2*i-1)));}return 4*sum;}}//exercise 5.17package fivechapterexercise2;public class seventh {public static void main(String[] args) {// TODO Auto-generated method stubprintMatrix(3);}public static void printMatrix(int n){for(int i=1;i<=n;i++){for(int j=1;j<=n;j++){System.out.print((int)(Math.random()*2)+" "); }System.out.println();}}}//exercise 5.18package fivechapterexercise2;public class eighth {public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println("number\t\tsqir");for(int i=0;i<=10;i++){System.out.println(2*i+"\t\t"+Math.sqrt(2*i));}}}//exercise 5-19package fivechapterexercise2;public class ninth {public static void main(String[] args) {// TODO Auto-generated method stubdouble side1=2,side2=3,side3=4;System.out.println("side1=2,side2=3,side3=4 is a triangle?"+isvalid(side1,side2,side3));}public static boolean isvalid(double side1,double side2,double side3){if(side1<side2){double temp=side1;side1=side2;side2=temp;}if(side1<side3){double temp=side1;side1=side3;side3=temp;}if(side1<side2+side3)return true;elsereturn false;}public static double area(double side1,double side2,double side3){double s=(side1+side2+side3)/2;//calculation areadouble area=Math.pow(s*(s-side1)*(s-side2)*(s-side3),0.5);return area;}}//exercise 5-20package fivechapterexercise2;public class tenth {public static void main(String[] args) {// TODO Auto-generated method stubfinal double RADIANS=Math.PI/180.0;int angle=0;System.out.println("angle\tsine\tcosine");for(int i=0;i<=36;i++){System.out.println(angle+"\t"+Math.sin(angle*RADIANS)+"\t"+Math.cos(angle*RADIANS)); angle += 10;}}}//exercise 5-21package fivechapterexercise3;import java.util.Scanner;//not precisepublic class first {public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);System.out.print("Enter ten numbers:");double []number=new double[10];for(int i=0;i<10;i++){number[i]=in.nextDouble();}System.out.println("The mean is "+average(number));System.out.println("The standard deviation is "+standarddeviation(number)); }public static double average(double ...average){double sum=0;for(int i=0;i<average.length;i++){sum=sum+average[i];}return sum/average.length;}public static double standarddeviation(double ...number){double sum=0;double squaresum=0;for(int i=0;i<number.length;i++){squaresum += Math.sqrt(number[i]);sum += number[i];}double num1=squaresum-Math.sqrt(sum)/(number.length);double num2=num1/(number.length-1);double calculation=Math.pow(num2,0.5);return calculation;}}//exercise 5-22package fivechapterexercise3;public class second {public static void main(String[] args){System.out.println("sqrt of 4 is "+sqrt(4));}public static double sqrt(double number){double lastguess=1;double reduce=1;while (reduce>0.00000001){double nextguess=(lastguess+(number/lastguess))/2;reduce=nextguess-lastguess;lastguess=nextguess;}return lastguess;}}//exercise 5.23package fivechapterexercise3;import chenqingyuan.RandomCharacter;public class third {public static void main(String[] args) {// TODO Auto-generated method stubfor(int i=0;i<100;i++){if(i%10==0)System.out.println();System.out.print(RandomCharacter.getRandomUpperCaseLetter()+" "); }System.out.println("\n\n");for(int i=0;i<100;i++){if(i%10==0)System.out.println();System.out.print(RandomCharacter.getRandomDigitCharacter()+" ");}}}//exercise 5.26package fivechapterexercise3;import chenqingyuan.math;public class sixth {public static void main(String[] args) {// TODO Auto-generated method stubint count=0;int integer=1;while(count<100){if(math.isPrime(integer)&&math.isPalindrome(integer)){if(count%10==0)System.out.println();System.out.print(integer+" ");count++;}integer++;}}}//exercise 5-27package fivechapterexercise3;import chenqingyuan.math;public class seventh {public static void main(String[] args) {// TODO Auto-generated method stubint count=0;int integer=1;while(count<100){if(math.isPrime(integer)&&math.isPrime(math.reverse(integer))&&!math.isPalindrome(integer)){if(count%10==0)System.out.println();System.out.print(integer+" ");count++;}integer++;}}}package fivechapterexercise3;public class eifhth {public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println("p\t\t2^p-1");for(int p=1;p<=31;p++){int number=(int)Math.pow(2,p)-1;if(chenqingyuan.math.isPrime(number))System.out.println(p+"\t\t"+number);}}}//exercise 5.29package fivechapterexercise3;public class ninth {public static void main(String[] args) {// TODO Auto-generated method stubint num1=(int)(Math.random()*6)+1;int num2=(int)(Math.random()*6)+1;int sum=num1+num2;System.out.print("You rolled "+num1+" + "+num2+" = "+sum);System.out.println();if(sum==3||sum==12){System.out.println("You lose");System.exit(0);}else if(sum==7||sum==11){System.out.println("You win");System.exit(0);}else{while(true){int num3=(int)(Math.random()*6)+1;int num4=(int)(Math.random()*6)+1;int add=num3+num4;if(sum==add){System.out.println("point is "+sum);System.out.print("You rolled "+num3+" + "+num4+" = "+add);System.out.println();System.out.println("You win");System.exit(0);}else if (add==7){System.out.println("point is "+sum);System.out.print("You rolled "+num3+" + "+num4+" = "+add); System.out.println();System.out.println("You lose");System.exit(0);}}}}}//exercise 5.30package fivechapterexercise3;import chenqingyuan.math;public class tenth {public static void main(String[] args) {// TODO Auto-generated method stubfor(int i=1;i<1000;i++){if(math.isPrime(i)&&math.isPrime(i+2))System.out.println("("+i+","+(i+2)+")");}}}//exercise 5.32package fivechapterexercise4;public class second {public static void main(String[] args) {// TODO Auto-generated method stubint count=0;for(int i=1;i<=10000;i++){int num1=(int)(Math.random()*6)+1;int num2=(int)(Math.random()*6)+1;int sum=num1+num2;if(sum==3||sum==12){continue;}else if(sum==7||sum==11){count++;continue;}else{while(true){int num3=(int)(Math.random()*6)+1;int num4=(int)(Math.random()*6)+1;int add=num3+num4;if(sum==add){count++;break;}else if (add==7){break;}}}}System.out.println("The number if times you win is "+count);}}//exercise 5.33package fivechapterexercise4;import chenqingyuan.math;//System.currentTimeMillis() display is USA timepublic class third {public static void main(String[] args) {// TODO Auto-generated method stublong millisecond=System.currentTimeMillis();long second=millisecond/1000%60;long minute=millisecond/1000/60%60;//+8 is to solve the time differencelong hour=(millisecond/3600/1000+8)%24;long day=(millisecond/3600/1000+8)/24;//judge yearlong daya=day-730;long day1=daya%1461;long count=daya/1461;//judge yearlong years=1970+2+4*count;if(day1>366){years =years+1;day1 -= 366;}while(day1>365){years +=1;day1 -= 365;}//resolve error !!To solve the time differenceday1 +=1;//judge monthint month=1;int mark;while(true){if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){mark=(int)day1/32;if(mark!=0){day1 -= 31;month++;}elsebreak;}else if(month==2){int numberofmonth=0;if(!math.isLeapYear((int)years))numberofmonth=28;elsenumberofmonth=29;mark=(int)day1/(numberofmonth+1);if(mark!=0){day1 -= numberofmonth;month++;}elsebreak;}else {mark=(int)day1/31;if(mark!=0){day1 -= 30;month++;}elsebreak;}}System.out.println("Current date and time is "+math.getMonthName(month)+" "+day1+","+years+" "+hour+":"+minute+":"+second); }}//exercise 5.35package fivechapterexercise4;import java.util.Scanner;public class fifth {public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);System.out.print("please input side:");int side=in.nextInt();System.out.println("This area is "+area(side));}public static double area(int side){double molecular=5*side*side;double denominator=4*Math.tan(Math.PI/5);return molecular/denominator;}}//exercise 5.36package fivechapterexercise4;import java.util.Scanner;public class sixth {public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);System.out.print("input number of side and side:");int numberofside=in.nextInt();int side=in.nextInt();System.out.println("This area is "+area(numberofside,side)); }public static double area(int n,int side){double molecular=n*side*side;double denominator=4*Math.tan(Math.PI/n);return molecular/denominator;}}。

java课后习题答案

java课后习题答案

java课后习题答案java课本课后习题答案第五章继承、接口与泛型1、子类在什么情况下可以继承父类的友好成员?答:父子类在同一包中时子类可以继承父类的友好成员。

2、子类通过什么办法,可以隐藏继承的成员变量。

答:子类成员变量与父类成员变量同名。

3、子类重写继承方法的规则是什么?答:重写隐藏父类的方法需:返回的数据类型相同,参数的个数相同,并且类型相同。

如果重写父类的方法后参数的个数或类型不同会出现子类方法的重载。

4.子类的构造方法的第一条语句是什么?答:如果需要调用父类构造方法,则应是用super关键词调用父类的构造方法。

5、子类一旦重写了继承的方法,就会隐藏继承的方法。

是这样吗?答:不一定。

在参数的个数或类型不同时会产生重载。

如果只有返回值的类型不同,将会产生编译错误。

(5)子类隐藏父类的方法,参数必须______相同并且__________相同.答:个数,类型6、子类重写继承方法时,可以降低方法的权限吗?答:重写继承方法时不能降低访问权限。

7、简述关键字super的用法。

答:1)子类调用父类的构造方法。

2)子类对象引用被隐藏了的父类方法,或成员变量。

8.假设父类有一个方法:Public double f(double x, double y){return x+y;}是否允许子类再声明如下的方法:Public float f(double x, double y){return 23;}答:不允许。

9、父类的final方法可以被子类重写吗?答:不可以10、什么类中可以有abstract方法?答:被abstract修饰的类。

接口中也可以有abstract方法11、什么叫做对象的上转型对象?答:用子类的构造方法构造出来的对象,赋值给父类对象。

12、什么叫接口回调?答:用实现接口的类创建的对象,赋值给该接口声明的接口变量。

13、与类有关的匿名类一定是该类的子类吗?与接口有关的匿名类一定是实现该接口的一个类吗?答:一定,因为类创建对象时,除了构造方法还有类体,此类体被认为是该类的一个子类去掉类声明后的类体。

Python语言程序设计(美-梁勇)第5章习题解答

Python语言程序设计(美-梁勇)第5章习题解答

Python语言程序设计(美-梁勇)第5章习题解答第5章循环5.1分析下面的代码。

在A、B、C处count<100总为true,总为false,还是有时true有时false?Count = 0While count < 100:#APrint ‘’pramming is fun!Count += 1#B#C答:A处一直为true,B处有时为真有时为假,C处一直为假。

5.2如果把程序清单5-3中的第8行的guess初始化为0,错在哪里?答:产生的随机数有可能为0,此时循环将不会执行。

5.3下边的循环体被重复了多少次?每次循环的输出结果是多少?答:a、循环体被重复无限次,没有输出结果;B、循环体被重复无限次,没有输出结果;c、循环体被执行了9次,输出结果为2\n 4\n 6\n 8(4行)5.4指出下面代码的错误:答:a、b均为死循环,c没有循环体。

5.5假设输入值为“2 3 4 5 0”(每行一个数),下面代码的输出结果是什么?答:5 0(每行一个数)5.6假设输入值为“2 3 4 5 0”(每行一个数),下面代码的输出结果是什么?答:14 4(每行一个数)5.7你能把任何一个for循环转换为while循环吗?列出for循环的优点。

答:可以。

For循环的优点是更加简洁和可实现性。

编译器产生的代码可以比while循环更高效的执行。

5.8将下面的for循环转换为while循环。

Sum = 0 答:sum = 0For i in range(1001): i = 0Sum = sum + i while i < 1001:Sum = sum + ii += 15.9你能将任意的while循环转换成for循环吗?将下面这个while 循环转换成for循环。

i = 1 答:sum = 0Sum = 0 for i in range(1, 1000):While sum < 1000: sum = sum + i Sum = sum + ii +=15.10统计下面循环的迭代次数:答:a、n次b、n次c、n - 5 d、ceil((n - 5) / 3)5.12如果你知道一个数n1的公约数不可能大于n1/2,你就可以试图使用下面的循环来改善你的程序:K = 2While k <= n1 / 2 and k <= n2 / 2:If n1 % k == 0 and n2 % k ==0:gcd = kK += 1这个程序是错误的,你能找出原因吗?答:当n1=3,n2=3时,程序找出的最大公约数是1,与正确答案不符。

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

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

《Java语言程序设计(基础篇)》(第10版梁勇著)第五章练习题答案5.1public class Exercise05_01 {public static void main(String[] args) {int countPositive = 0, countNegative = 0;int count = 0, total = 0, num;Scanner input = new Scanner(System.in);System.out.print("Enter integers ending with 0: ");num = input.nextInt();while (num != 0) {if (num > 0)countPositive++;else if (num < 0)countNegative++;total += num;count++;// Read the next numbernum = input.nextInt();}if (count == 0)System.out.println("no numbers are entered except 0");else {System.out.println("The number of positives is " + countPositive); System.out.println("The number of negatives is " + countNegative); System.out.println("The total is " + total);System.out.println("The average is " + total * 1.0 / count);}}}5.1附加public class Exercise05_01Extra {public static void main(String[] args) {final int NUMBER_OF_TRIALS = 10000000;int numberOfHits = 0;for (int i = 0; i < NUMBER_OF_TRIALS; i++) {double x = Math.random() * 2.0 - 1;double y = Math.random() * 2.0 - 1;if (x * x + y * y <= 1)numberOfHits++;}double pi = 4.0 * numberOfHits / NUMBER_OF_TRIALS;System.out.println("PI is " + pi);}}5.2public class Exercise05_02 {public static void main(String[] args) {int correctCount = 0; // Count the number of correct answersint count = 0; // Count the number of questionsjava.util.Scanner input = new java.util.Scanner(System.in);long startTime = System.currentTimeMillis();while (count < 10) {// 1. Generate two random single-digit integersint number1 = 1 + (int)(Math.random() * 15);int number2 = 1 + (int)(Math.random() * 15);// 2. Prompt the student to answer 搘hat is number1 ?number2??System.out.print("What is " + number1 + " + " + number2 + "? ");int answer = input.nextInt();// 3. Grade the answer and display the resultString replyString;if (number1 + number2 == answer) {replyString = "You are correct!";correctCount++;}else {replyString = "Your answer is wrong.\n" + number1 + " + "+ number2 + " should be " + (number1 + number2);}System.out.println(replyString);// Increase the countcount++;}System.out.println("Correct count is " + correctCount);long endTime = System.currentTimeMillis();System.out.println("Time spent is " + (endTime - startTime) / 1000 + " seconds");}}5.2附加public class Exercise05_02Extra {public static void main(String[] args) {final int NUMBER_OF_TRIALS = 1000000;int numberOfHits = 0;for (int i = 0; i < NUMBER_OF_TRIALS; i++){double x = Math.random() * 2.0 - 1;double y = Math.random() * 2.0 - 1;if (x < 0)numberOfHits += 1;else if (!(x > 1 || x < 0 || y > 1 || y < 0)) {double slope = (1.0 - 0) / (0 - 1.0);double x1 = x + -y * slope;if (x1 <= 1)numberOfHits += 1;}}System.out.println("The probability in Region 1 and 3 is " +(1.0 * numberOfHits / NUMBER_OF_TRIALS));}/*static boolean isInRegion3(double x, double y) {if (x > 1 || x < 0 || y > 1 || y < 0)return false;else {double slope = (1.0 - 0) / (0 - 1.0);double x1 = x + -y * slope;if (x1 <= 1)return true;elsereturn false;}}*/}5.3public class Exercise05_03 {public static void main(String[] args) {System.out.printf("%-14s%-10s\n", "Kilograms", "Pounds");System.out.println("--------------------");int kilograms = 1;while (kilograms < 200) {System.out.printf("%-14d%-10.1f\n", kilograms, kilograms * 2.2); kilograms += 2;}/** Alternatively use for loopfor (int kilograms = 1; kilograms <= 199; kilograms += 2) {System.out.println(kilograms + "\t\t" + kilograms * 2.2);}*/}}5.3附加public class Exercise05_03Extra {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter the number of seconds: ");int numberOfSeconds = input.nextInt();long currentTime = System.currentTimeMillis() / 1000;long endTime = currentTime + numberOfSeconds * 1000;while (currentTime <= endTime) {if ((endTime - currentTime) % 1000 == 0) {if (endTime - currentTime > 1000)System.out.println((endTime - currentTime) / 1000 + " secondsremaining");else if (endTime - currentTime == 1000)System.out.println("1 second remaining");}currentTime += 1;}System.out.println("Stopped");}}5.4public class Exercise05_04 {public static void main(String[] args) {System.out.println("Miles\t\tKilometers");System.out.println("-------------------------------");// Use while loopint miles = 1;while (miles <= 10) {System.out.println(miles + "\t\t" + miles * 1.609);miles++;}/** Alternatively use for loopfor (int miles = 1; miles <= 10; miles++) {System.out.println(miles + "\t\t" + miles * 1.609);}*/}}5.4附加public class Exercise05_04Extra {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);while (true) {System.out.println("Main menu");System.out.println("1: Addition");System.out.println("2: Subtraction");System.out.println("3: Multiplication");System.out.println("4: Division");System.out.println("5: Exit");System.out.print("Enter a choice: ");int choice = input.nextInt();int number1 = (int)(Math.random() * 10);int number2 = (int)(Math.random() * 10);int answer;if (choice == 1) {System.out.print("What is " + number1 + " + " + number2 + "? "); answer = input.nextInt();if (number1 + number2 == answer)System.out.println("Correct");elseSystem.out.println("Your answer is wrong. The correct answer is " + (number1 + number2));}else if (choice == 2) {if (number1 < number2) { // Swap number1 with number2int temp = number1;number1 = number2;number2 = temp;}System.out.print("What is " + number1 + " - " + number2 + "? "); answer = input.nextInt();if (number1 - number2 == answer)System.out.println("Correct");elseSystem.out.println("Your answer is wrong. The correct answer is " + (number1 - number2));}else if (choice == 3) {System.out.print("What is " + number1 + " * " + number2 + "? "); answer = input.nextInt();if (number1 * number2 == answer)System.out.println("Correct");elseSystem.out.println("Your answer is wrong. The correct answer is " + (number1 * number2));}else if (choice == 4) {while (number2 == 0)number2 = (int)(Math.random() * 10);System.out.println("What is " + number1 + " / " + number2 + "? "); answer = input.nextInt();if (number1 / number2 == answer)System.out.println("Correct");elseSystem.out.println("Your answer is wrong. The correct answer is " + (number1 / number2));}else if (choice == 5)break;}}}5.5public class Exercise05_05 {public static void main(String[] args) {System.out.printf("%10s%10s | %10s%10s\n", "kilograms", "pounds", "pounds", "kilograms");System.out.println("---------------------------------------------");// Use while loopint kilograms = 1;int pounds = 20;int count = 1;while (count <= 100) {System.out.printf("%10d%10.3f | %10d%10.3f\n", kilograms,kilograms * 2.2, pounds, pounds / 2.2);kilograms += 2;pounds += 5;count++;}/*** Alternatively use for loop int kilograms = 1; int pounds = 20; for (int * count = 1; count <= 100; kilograms += 2, pounds += 5, count++) {* System.out.println(kilograms + "\t\t" + kilograms * 2.2 + "\t|\t" + * pounds + "\t\t" + pounds / 2.2); }*/}}5.5附加public class Exercise05_05Extra {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Enter the number of sides: ");int n = input.nextInt();System.out.print("Enter the radius of the bounding circle: ");double radius = input.nextDouble();double angle = 0;System.out.print("The coordinates of the points on the polygon are ");for (int i = 0; i < n; i++) {double x = radius * Math.cos(angle);double y = radius * Math.sin(angle);System.out.println("(" + x + ", " + y + ")");angle += 2 * Math.PI / n;}}}5.6public class Exercise05_06 {public static void main(String[] args) {System.out.printf("%10s%10s | %10s%10s\n", "Miles", "Kilometers", "Kilometers", "Miles");System.out.println("---------------------------------------------");// Use while loopint miles = 1;int kilometers = 20;int count = 1;while (count <= 10) {System.out.printf("%10d%10.3f | %10d%10.3f\n", miles, miles * 1.609,kilometers, kilometers / 1.609);miles++;kilometers += 5;count++;}/** Use for loop int miles = 1; int kilometers = 20; for (int count = 1; * count <= 10; miles++, kilometers += 5, count++) {* System.out.printf("%10d%10.3f | %10d%10.3f\n", miles, miles * 1.609,* kilometers, kilometers / 1.609); }*/}}5.6附加public class Exercise05_06Extra {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Enter a genome string: ");String genome = input.nextLine();boolean found = false;int start = -1;for (int i = 0; i < genome.length() - 2; i++) {String triplet = genome.substring(i, i + 3);if (triplet.equals("ATG"))start = i + 3;else if ((triplet.equals("TAG") || triplet.equals("TAA") || triplet .equals("TGA")) && start != -1) {// A possible gene is foundString gene = genome.substring(start, i);if (gene.length() % 3 == 0) {// A gene is found and display the genefound = true;System.out.println(gene);start = -1; // Start to find the next gene in the genome}}}if (!found)System.out.println("no gene is found");}}5.7public class Exercise05_07 {public static void main(String[] args) {// Use a while loopdouble tuition = 10000;int count = 1;while (count <= 10) {tuition = tuition * 1.05;count++;}/*// Alternatively use a for loopdouble tuition = 10000;for (int i = 1; i <= 10; i++) {tuition = tuition * 1.05;}*/System.out.println("Tuition in ten years is " + tuition);double sum = tuition;for (int i = 2; i <= 4; i++) {tuition = tuition * 1.05;sum += tuition;}System.out.println("The four-year tuition in ten years is " + sum); }}5.7附加public class Exercise05_07Extra {public static void main(String[] args) {System.out.print("Enter a positive integer: ");Scanner input = new Scanner(System.in);int n = input.nextInt();int number = n;int factor = 2;int coefficient = 1;while (factor <= number) {if (number % (factor * factor) == 0) {coefficient *= factor;number = number / (factor * factor);}elsefactor++;}System.out.print("sqrt(" + n + ") is ");if (n == 1)System.out.println(1);else {if (coefficient > 1)System.out.print(coefficient);if (coefficient > 1 && number > 1)System.out.print("*");if (number > 1)System.out.print("sqrt(" + number + ")");}}}5.8public class Exercise05_08 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter the number of students System.out.print("Enter the number of students: ");int numOfStudents = input.nextInt();System.out.print("Enter a student name: ");String student1 = input.next();System.out.print("Enter a student score: ");double score1 = input.nextDouble();for (int i = 0; i < numOfStudents - 1; i++) {System.out.print("Enter a student name: ");String student = input.next();System.out.print("Enter a student score: ");double score = input.nextDouble();if (score > score1) {student1 = student;score1 = score;}}System.out.println("Top student " +student1 + "'s score is " + score1);}}5.8附加public class Exercise05_08Extra {public static void main(String[] args) {String vehiclePlateNumber = "";for (int i = 0; i < 7; i++) {char ch = Math.random() < 0.5 ?(char)('A' + (int)(Math.random() * 26)) : (char)('0' + (int)(Math.random() * 10));vehiclePlateNumber += ch;}System.out.println("A random vehicle plate number: "+ vehiclePlateNumber);}}5.9public class Exercise05_09 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter the number of studentsSystem.out.print("Enter the number of students: ");int numberOfStudents = input.nextInt();System.out.print("Enter a student name: ");String student1 = input.next();System.out.print("Enter a student score: ");double score1 = input.nextDouble();System.out.print("Enter a student name: ");String student2 = input.next();System.out.print("Enter a student score: ");double score2 = input.nextDouble();// Make sure that student1 is for the highest// and student2 is for the second highestif (score1 < score2) {// SwapString tempString = student1;double tempScore = score1;student1 = student2;score1 = score2;student2 = tempString;score2 = tempScore;}for (int i = 0; i < numberOfStudents - 2; i++) {System.out.print("Enter a student name: ");String student = input.next();System.out.print("Enter a student score: ");double score = input.nextDouble();if (score > score1) {student2 = student1; // student1 now is the second highestscore2 = score1;student1 = student; // new student becomes the highestscore1 = score;}else if (score > score2) {student2 = student; // new student becomes the second highest score2 = score;}}System.out.println("Top two students:");System.out.println(student1 + "'s score is " + score1);System.out.println(student2 + "'s score is " + score2);}}5.9附加public class Exercise05_09Extra {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a string: ");String s = input.nextLine();int count = 0;for (int i = 0; i < s.length() - 1; i++)if (s.charAt(i) == s.charAt(i + 1))count++;System.out.println("The number of consecutive repeating characters is " + count);}}5.10public class Exercise05_10 {public static void main(String[] args) {int count = 1;for (int i = 100; i <= 1000; i++)if (i % 5 == 0 && i % 6 == 0)System.out.print((count++ % 10 != 0) ? i + " ": i + "\n");}}5.10附加public class Exercise05_10Extra {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a string: ");String s = input.nextLine();int maxOccurrenceCount = 1;char maxOccurrenceChar = s.charAt(0);int currentOccurrenceCount = 1;char currentCh = s.charAt(0);for (int i = 0; i < s.length() - 1; i++) {if (currentCh == s.charAt(i + 1))currentOccurrenceCount++;if (currentCh != s.charAt(i + 1) ||(i == s.length() - 2 && currentCh == s.charAt(i + 1))){if (currentOccurrenceCount > maxOccurrenceCount) {maxOccurrenceCount = currentOccurrenceCount;maxOccurrenceChar = currentCh;}currentCh = s.charAt(i + 1);currentOccurrenceCount = 1;}}System.out.print("The first longest consecutive repeating character substring is ");for (int i = 0; i < maxOccurrenceCount; i++)System.out.print(maxOccurrenceChar);}}5.11public class Exercise05_11 {public static void main(String[] args) {int count = 1;int i = 100;while (i <= 200) {if (i % 5 == 0 ^ i % 6 == 0) {System.out.print((count % 10 != 0) ? i + " ": i + "\n");count++;}i++;}/* for loopfor (int i = 100; i <= 200; i++)if (i % 5 == 0 ^ i % 6 == 0)System.out.print((count++ % 10 != 0) ? i + " ": i + "\n"); */}}5.11附加public class Exercise05_11Extra {public static void main(String[] args) {System.out.printf("%-15s%-15s\n", "RealNumber", "SquareRoot"); System.out.println("-------------------------------");for (int num = 0; num <= 20; num++) {System.out.printf("%-15d%-15.4f\n", num, Math.sqrt(num));}}}5.12/** Find the smallest number such that n*n < 12000 */public class Exercise05_12 {// Main methodpublic static void main(String[] args) {int i = 1;while (i * i <= 12000 ) {i++;}System.out.println("This number is " + i);}}5.12附加public class Exercise05_12Extra {public static void main(String[] args) {System.out.println("Degree\tSin\t\tCos");for (int degree = 0; degree <= 360; degree += 10) {System.out.printf("%-3d\t%6.4f\t\t%6.4f\n", degree,Math.sin(degree * Math.PI / 180),Math.cos(degree * Math.PI / 180));}}/*public static double format(double d, int position) {return Math.round(d * Math.pow(10, position)) / Math.pow(10, position); } */}5.13/** Finding the largest n such that n^3 < 12000) */public class Exercise05_13 {public static void main(String[] args) {int i = 1;while (i * i * i < 12000) {i++;}// i^3 >= 12000// (i-1)^3 < 12000System.out.println("This number is " + (i - 1));}}5.13附加public class Exercise05_13Extra {public static void main(String[] args) {for (int i = 0; i < 10; i++) {System.out.println((int)(Math.random() * 101));}}}5.14public class Exercise05_14 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Enter n1System.out.print("Enter the first number: ");int n1 = input.nextInt();// Enter n2System.out.print("Enter the second number: ");int n2 = input.nextInt();int d = (n1 < n2) ? n1 : n2;for (; d >= 1; d--) {if ((n1 % d == 0) && (n2 % d == 0)) {break;}}System.out.println("GCD of " + n1 + " and " + n2 + " is "+ d);}}5.14附加public class Exercise05_14Extra {public static void main(String[] args) {double value = Math.random();while (value <= 0.75) {System.out.println(value);value = Math.random();}System.out.println(value);}}5.15public class Exercise05_15 {public static void main(String[] args) {int count = 1;for (int i = '!'; i < '~'; i++) {System.out.print((count++ % 10 != 0) ? (char)i + " " :(char)i + "\n");}}}5.16public class Exercise05_16 {// Main methodpublic static void main(String args[]) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter a positive integerSystem.out.print("Enter a positive integer: ");int number = input.nextInt();// Find all the smallest factors of the integerSystem.out.println("The factors for " + number + " is");int factor = 2;while (factor <= number) {if (number % factor == 0) {number = number / factor;System.out.println(factor);}else {factor++;}}}}5.17public class Exercise05_17 {public static void main(String[] args) {// Create a ScannerScanner input = new Scanner(System.in);// Prompt the user to enter the number of linesSystem.out.print("Enter the number of lines: ");int numberOfLines = input.nextInt();if (numberOfLines < 1 || numberOfLines > 15) {System.out.println("You must enter a number from 1 to 15"); System.exit(1);}// Print linesfor (int row = 1; row <= numberOfLines; row++) {// Print (NUMBER_OF_LINES ?row) leading spacesfor (int column = 1; column <= numberOfLines - row; column++) System.out.print(" ");// Print leading numbers row, row ?1, ..., 1for (int num = row; num >= 1; num--)System.out.print((num >= 10) ? " " + num : " " + num);// Print ending numbers 2, 3, ..., row ?1, rowfor (int num = 2; num <= row; num++)System.out.print((num >= 10) ? " " + num : " " + num);// Start a new lineSystem.out.println();}}}5.18public class Exercise05_18 {/** Print Pattern I */public static void main(String[] args) {for (int i = 1; i <= 6; i++) {for (int j = 1; j <= i; j++)System.out.print(j + " ");System.out.println();}}}解法2:public class Exercise05_18d {/** Print Pattern D */public static void main(String[] args) {for (int i = 1; i <= 6; i++) {for (int j = 1; j <= 6; j++)System.out.print(i <= j ? j + " " : " ");System.out.println();}}}5.19public class Exercise05_19 {public static void main(String[] args) {int number = 0; // Number to printfor (int row = 0; row <= 7; row++) {// Pad leading blanksfor (int col = 1; col <= 7 - row; col++)System.out.printf("%4s", " ");// Print left half of the rowfor (int col = 0; col <= row; col++) {number = (int)Math.pow(2, col);System.out.printf("%4d", number);}// Print the right half of the rowfor (int col = row - 1; col >= 0; col--) {number = (int)Math.pow(2, col);System.out.printf("%4d", number);}// Start a new lineSystem.out.print('\n');}}}5.20public class Exercise05_20 {// Main methodpublic static void main(String[] args) {int count = 1; // Count the number of prime numbersint number = 2; // A number to be tested for primenessboolean isPrime = true; // If the current number is prime?System.out.println("The prime numbers from 2 to 1000 are \n");// Repeatedly test if a new number is primewhile (number <= 1000) {// Assume the number is primeisPrime = true;// Set isPrime to false, if the number is primefor (int divisor = 2; divisor <= number / 2; divisor++) {if (number % divisor == 0) { // If true, the number is prime isPrime = false;break; // Exit the for loop}}// Print the prime number and increase the countif (isPrime) {if (count%8 == 0) {// Print the number and advance to the new lineSystem.out.println(number);}elseSystem.out.print(number + " ");count++; // Increase the count}// Check if the next number is primenumber++;}}}5.21public class Exercise05_21 {// Main methodpublic static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Enter loan amountSystem.out.print("Enter loan amount, for example 120000.95: ");double loanAmount = input.nextDouble();// Enter number of yearsSystem.out.print("Enter number of years as an integer, \nfor example 5: ");// Convert string to intint numOfYears = input.nextInt();// Display the headerSystem.out.printf("%-20s%-20s%-20s\n", "Interest Rate", "Monthly Payment", "Total Payment");for (double annualInterestRate = 5.0; annualInterestRate <= 8.0;annualInterestRate += 1.0 / 8) {// Obtain monthly interest ratedouble monthlyInterestRate = annualInterestRate / 1200;// Compute mortgagedouble monthlyPayment = loanAmount * monthlyInterestRate /(1 - (Math.pow(1 / (1 + monthlyInterestRate), numOfYears * 12)));double totalPayment = monthlyPayment * numOfYears * 12;// Display resultsSystem.out.printf("%5.3f%c %20.2f %20.2f\n", annualInterestRate, '%', monthlyPayment, totalPayment);}}}5.22public class Exercise05_22 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Enter loan amountSystem.out.print("Enter loan amount, for example 120000.95: ");double loanAmount = input.nextDouble();// Enter number of yearsSystem.out.print("Enter number of years as an integer, for example 5: ");int numOfYears = input.nextInt();// Enter yearly interest rateSystem.out.print("Enter yearly interest rate, for example 8.25: ");double annualInterestRate = input.nextDouble();// Obtain monthly interest ratedouble monthlyInterestRate = annualInterestRate/1200;// Compute mortgagedouble monthlyPayment = loanAmount*monthlyInterestRate /(1 - (Math.pow(1 / (1 + monthlyInterestRate), numOfYears * 12)));double balance = loanAmount;double interest;double principal;System.out.println("Monthly Payment: " + (int)(monthlyPayment * 100) / 100.0 );System.out.println("Total Payment: " + (int)(monthlyPayment * 12 * numOfYears * 100) / 100.0 + "\n" );// Display the headerSystem.out.println("Payment#\tInterest\tPrincipal\tBalance");for (int i = 1; i <= numOfYears * 12; i++) {interest = (int)(monthlyInterestRate * balance * 100) / 100.0;principal = (int)((monthlyPayment - interest) * 100) / 100.0;balance = (int)((balance - principal) * 100) / 100.0;System.out.println(i + "\t\t" + interest+ "\t\t" + principal + "\t\t" + balance);}}}5.23public class Exercise05_23 {final static int N = 50000;public static void main (String[] args) {// Backward computingdouble sum = 0.0;for (int i = N; i >= 1; i--)sum += 1.0 / (double)(i);System.out.println("The result of the backward computation " + sum);// Forward computingdouble sum1 = 0.0;for (int i = 1; i <= N; i++)sum1 += 1.0 / (double)(i);System.out.println("The result of the forward computation " + sum1);double difference = sum - sum1;System.out.println("difference is " + difference);}/*public static double backward() {double sum = 0.0;for (int i = N; i >= 1; i--)sum += 1.0 / (double)(i);return sum;}static double forward() {double sum = 0.0;for (int i = 1; i <= N; i++)sum += 1.0 / (double)(i);return sum;} */}5.24public class Exercise05_24 {public static void main(String[] args) {double sum = 0;for (int i = 1; i <= 97; i += 2)sum += 1.0 * i / (i + 2);System.out.println("sum is " + sum);}}5.25public class Exercise05_25 {public static void main(String[] args) {double pi = 1;。

相关文档
最新文档