《Java語言程序設(shè)計(基礎(chǔ)篇)》(第10版梁勇著)第十八章練習(xí)題答案_第1頁
《Java語言程序設(shè)計(基礎(chǔ)篇)》(第10版梁勇著)第十八章練習(xí)題答案_第2頁
《Java語言程序設(shè)計(基礎(chǔ)篇)》(第10版梁勇著)第十八章練習(xí)題答案_第3頁
《Java語言程序設(shè)計(基礎(chǔ)篇)》(第10版梁勇著)第十八章練習(xí)題答案_第4頁
《Java語言程序設(shè)計(基礎(chǔ)篇)》(第10版梁勇著)第十八章練習(xí)題答案_第5頁
免費預(yù)覽已結(jié)束,剩余52頁可下載查看

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

1、 Java 語言程序設(shè)計(基礎(chǔ)篇) (第 10 版 梁勇 著)第十八章練習(xí)題答案18.1import java.math.*;import java.util.*;public class Exercise18_01 public static void main(String args) Scanner input = new Scanner(System.in);System.out.print( "Enter an integer of any size: ");String numberString = input.nextLine();BigInteger big

2、Number = new BigInteger(numberString);System.out.println(factorial(bigNumber); public static BigInteger factorial(BigInteger i) if (i.equals(BigInteger.ZERO) return BigInteger.ONE;else return i.multiply(factorial(i.subtract(BigInteger.ONE); 18.2/ Exercise18_02.java: Iterative solution for the Fibona

3、cci numberpublic class Exercise18_02 public static void main(String args) System.out.println("The fibonacci(10) is "+ fib(10);public static long fib( int n) int f0 = 0, f1 = 1, currentFib;if (n = 0)return0;if (n = 1)return1;for ( int i = 2; i <= n; i+) currentFib = f0 + f1;f0 = f1;f1 =

4、currentFib;return f1;18.3/ Exercise18_03.java: Find the GCD of two integersimport java.util.Scanner;public class Exercise18_03 public static void main (String args) Scanner input =new Scanner(System.in);/ Enter the first numberSystem.out.print("Enter the first number: ");int m = input.next

5、Int();/ Enter the second numberSystem.out.print("Enter the second number: ");int n = input.nextInt();is "+System.out.println("The GCD of "+ m +" and "+ n +gcd(m, n);public static int gcd( int m, int n) if (m % n = 0) return n;elsereturn gcd(n, m % n);18.4public cla

6、ss Exercise18_04 public static void main(String args) for ( int i = 1; i <= 10; i+)System.out.println(m(i);public static double m( int i) if (i = 1)return 1;elsereturn m(i - 1) + 1.0 / i;18.5public class Exercise18_05 public static void main(String args) for ( int i = 1; i <= 10; i+)System.out

7、.println(m(i);public static double m( int i) if (i = 1)return 1.0 / 3;elsereturn m(i - 1) + i * 1.0 / (2 * i + 1);18.6public class Exercise18_06 public static void main(String args) for ( int i = 1; i <= 10; i+)System.out.println(m(i);public static double m( int i) if (i = 1)return 1.0 / 2;elsere

8、turn m(i - 1) + i * 1.0 / (i + 1);18.7import java.util.Scanner;public class Exercise18_07 static int count = 0;public static void main(String args) / Read the indexScanner input =new Scanner(System.in);System.out.print("Enter an index for the Fibonacci number: ");int index = input.nextInt(

9、);System.out.println("Fibonacci number at index "+ index +" is "+fib(index);System.out.println("Number of times fib is invoked? "+ count);/* The method for finding the Fibonacci number */ public static long fib( long index) count+;if (index = 0)/ Base casereturn 0;else

10、if (index = 1)/ Base casereturn 1;else / Reduction and recursive callsreturn fib(index - 1) + fib(index - 2);18.8import java.util.Scanner;public class Exercise18_08 public static void main(String args) Scanner input =new Scanner(System.in);System.out.print("Enter an integer: ");int i = inp

11、ut.nextInt();reverseDisplay(i);public static void reverseDisplay( int value) if (value != 0) System.out.print(value % 10);value = value / 10;reverseDisplay(value);18.9import java.util.Scanner;public class Exercise18_09 public static void main(String args) Scanner input =new Scanner(System.in);System

12、.out.print("Enter a string: ");String i = input.nextLine();reverseDisplay(i);public static void reverseDisplay(String value) if (value.length() > 0) System.out.print(value.charAt(value.length() - 1);reverseDisplay(value.substring(0, value.length() - 1);18.10import java.util.Scanner;publ

13、ic class Exercise18_10 public static void main(String args) Scanner input =new Scanner(System.in);System.out.print("Enter a string: ");String s = input.nextLine();System.out.print("Enter a character: ");char ch = input.nextLine().charAt(0);int times = count(s, ch);timesSystem.out

14、.println(ch +" appears "+ times + (times > 1time " ) + "in "+ s);public static int count(String str,char a) int result = 0;if (str.length() > 0)result = count(str.substring(1), a) +(str.charAt(0) = a) ? 1 : 0);return result; 18.11import java.util.Scanner;public class E

15、xercise18_11 public static void main(String args) Scanner input =new Scanner(System.in);System.out.print("Enter an integer: ");int i = input.nextInt();+ sumDigits(i);System.out.println("The sum of digits in "+ i +" ispublic static int sumDigits( long n) int result = 0;if (n

16、!= 0) result = sumDigits(n / 10) + (int )(n % 10);return result; 18.12import java.util.Scanner;public class Exercise18_12 public static void main(String args) Scanner input =new Scanner(System.in);System.out.print("Enter a string: ");String s = input.nextLine();reverseDisplay(s);public sta

17、tic void reverseDisplay(String value) reverseDisplay(value, value.length() - 1);public static void reverseDisplay(String value,int high) if (high >= 0) System.out.print(value.charAt(high);reverseDisplay(value, high - 1);18.13import java.util.Scanner;public class Exercise18_13 public static void m

18、ain(String args) Scanner input =new Scanner(System.in);System.out.print("Enter 8 integers: ");int list = new int 8;for ( int i = 0; i < list.length; i+)listi = input.nextInt();System.out.println(largest(list);public static int largest( int list) return largest(list, list.length - 1);pub

19、lic static int largest( int list, int high) if (high = 0) return list0;else return Math.max(largest(list, high - 1), listhigh);18.14import java.util.Scanner;public class Exercise18_14 public static void main(String args) Scanner input =new Scanner(System.in);System.out.print("Enter a string: &q

20、uot;);String s = input.nextLine();System.out.println("The uppercase letters in "+ s +" iscountUppercase(s);public static int countUppercase(String str) return countUppercase(str, str.length() - 1);public static int countUppercase(String str,int high) if (high < 0)return 0;elseretur

21、n countUppercase(str, high - 1) + (Character.isUpperCase(str.charAt(high) ? 1 : 0); 18.15import java.util.Scanner;public class Exercise18_15 public static void main(String args) Scanner input =new Scanner(System.in);System.out.print("Enter a string: ");String s = input.nextLine();System.ou

22、t.print("Enter a character: ");char ch = input.nextLine().charAt(0);int times = count(s, ch);timesSystem.out.println(ch +" appears "+ times + (times > 1 ?time " ) + "in "+ s);publicstatic int count(String str,chara) returncount(str, a, str.length() - 1);publicst

23、atic int count(String str,chara, int high) int result = 0;if (high >= 0)result = count(str, a, high - 1) + (str.charAt(high) = a) ? 1 : 0);return result;18.16public class Exercise18_16 public static void main(String args) System.out.println(count(new char 'W' , 'e' , 'l' ,

24、 'c' , 'o' , 'm' , 'E' );public static int count( char chars) return count(chars, chars.length - 1);public static int count( char chars, int high) if (high >= 0) return count(chars, high - 1) +(Character.isUpperCase(charshigh) ? 1 : 0);elsereturn 0;18.17public clas

25、s Exercise18_17 public static void main(String args) System.out.println(count(new char 'W' , 'e' , 'l' , 'c' , 'o' , 'm' , 'E' ,'e' );public static int count( char chars, char ch) return count(chars, ch, chars.length - 1);public static

26、int count( char chars, char ch, int high) if (high >= 0) return count(chars, ch, high - 1) + (charshigh = ch) ? 1 : 0);elsereturn 0;18.18import java.util.Scanner;public class Exercise18_18 /* Main method */public static void main(String args) Scanner input =new Scanner(System.in);/ Read number of

27、 disks, nSystem.out.print("Enter number of disks: ");int n = input.nextInt();/ Find the solution recursivelySystem.out.println("The moves are:" );moveDisks(n, 'A' , 'B' , 'C' );System.out.println("The total number of moves is "+ count);static int

28、 count = 0;/* The method for finding the solution to move n disks from fromTower to toTower with auxTower */public static void moveDisks( int n, char fromTower,char toTower, char auxTower) count+;if (n = 1)/ Stopping conditionSystem.out.println("Move disk "+ n +" from "+fromTower

29、 +" to "+ toTower);else moveDisks(n - 1, fromTower, auxTower, toTower);System.out.println("Move disk "+ n +" from "+fromTower +" to "+ toTower);moveDisks(n - 1, auxTower, toTower, fromTower); 18.19import javafx.application.Application;import javafx.geometry.Po

30、int2D;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.BorderPane;import javafx.scene.layout.HBox;import javafx.scene.layout.Pane;import javafx.scene.paint.Color;import javafx.scene.shape.Polygon;import javafx.stage.Stage;public class

31、 Exercise18_19 extends Application private int order = -1;Override / Override the start method in the Application class publicvoid start(Stage primaryStage) SierpinskiTrianglePane trianglePane =new SierpinskiTrianglePane();Button btDown = new Button( "-" );Button btUp = new Button( "+

32、" );HBox hBox = new HBox(5);hBox.setAlignment(Pos.CENTER);hBox.getChildren().addAll(btDown, btUp);btUp.setOnAction(e -> trianglePane.setOrder(+order);btDown.setOnAction(e -> trianglePane.setOrder(-order);BorderPane borderPane =new BorderPane();borderPane.setCenter(trianglePane);borderPane

33、.setBottom(hBox);/ Create a scene and place it in the stageScene scene = new Scene(borderPane, 200, 210);primaryStage.setTitle("Exercise18_19" ); / Set the stage titleprimaryStage.setScene(scene);/ Place the scene in the stageprimaryStage.show();/ Display the stagescene.widthProperty().add

34、Listener(ov -> trianglePane.paint();scene.heightProperty().addListener(ov -> trianglePane.paint();/* Pane for displaying triangles */static class SierpinskiTrianglePaneextends Pane private int order = 0;/* Set a new order */publicvoid setOrder(int order) this .order = order;paint();SierpinskiT

35、rianglePane() protected void paint() / Select three points in proportion to the panel sizePoint2D p1 =new Point2D(getWidth() / 2, 10);Point2D p2 =new Point2D(10, getHeight() - 10);Point2D p3 =new Point2D(getWidth() - 10, getHeight() - 10);this .getChildren().clear();/ Clear the pane before redisplay

36、displayTriangles(order, p1, p2, p3);private void displayTriangles( int order, Point2D p1, Point2D p2, Point2D p3) if (order < 0) return ;if (order = 0) / Draw a triangle to connect three pointsPolygon triangle =new Polygon();triangle.getPoints().addAll(p1.getX(), p1.getY(), p2.getX(),p2.getY(), p

37、3.getX(), p3.getY();triangle.setStroke(Color.BLACK);triangle.setFill(Color.WHITE);this .getChildren().add(triangle);else / Get the midpoint on each edge in the trianglePoint2D p12 = p1.midpoint(p2);Point2D p23 = p2.midpoint(p3);Point2D p31 = p3.midpoint(p1);/ Recursively display three triangles disp

38、layTriangles(order - 1, p1, p12, p31); displayTriangles(order - 1, p12, p2, p23); displayTriangles(order - 1, p31, p23, p3);/* 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);18.

39、20import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.layout.Pane;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.stage.Stage;public class Exercise18_20 extends Application Override / Override the start method in the Application classpub

40、lic void start(Stage primaryStage) / Create a scene and place it in the stageScene scene = new Scene( new CirclePane(), 200, 200);primaryStage.setTitle("Exercise18_20" ); / Set the stage titleprimaryStage.setScene(scene);/ Place the scene in the stageprimaryStage.show();/ Display the stage

41、/* Pane for displaying triangles */static class CirclePane extends Pane private double radius = 80;public CirclePane() displayCircles();private void displayCircles() if (radius >= 5) Circle c =new Circle(100, 100, radius);c.setFill(Color.WHITE);c.setStroke(Color.BLACK);getChildren().add(c);radius

42、 -= 5;displayCircles();/* 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); 18.21import java.util.Scanner;public class Exercise18_21 public static void main(String args) Scanner i

43、nput =new Scanner(System.in);System.out.print("Enter a decimal integer: ");int decimal = input.nextInt();System.out.println(decimal +" is binary "+ decimalToBinary(decimal);public static String decimalToBinary(int value) if (value = 0) return "" ;elsereturn decimalToBin

44、ary(value / 2) + value % 2;18.22import java.util.Scanner;public class Exercise18_22 public static void main(String args) Scanner input =new Scanner(System.in);System.out.print("Enter a decimal integer: ");int decimal = input.nextInt();System.out.println(decimal +" is hex "+ decim

45、alToHex(decimal);public static String decimalToHex( int value) if (value = 0)return "" ;else return decimalToHex(value / 16) + decimalToHexChar(value % 16); public static char decimalToHexChar( int value) if (value >= 10 && value <=15)return ( char )( 'A' + value - 10

46、);elsereturn ( char )( '0' + value); 18.23import java.util.Scanner;public class Exercise18_23 public static void main(String args) Scanner input =new Scanner(System.in);System.out.print("Enter a binary number: ");String binary = input.nextLine();System.out.println(binary +" is

47、 decimal "+ binaryToDecimal(binary);public static int binaryToDecimal(String binaryString) return binaryToDecimal(binaryString, 0, binaryString.length() - 1);high) public static int binaryToDecimal(String binaryString,int low, intif (high < low)return 0;elsereturn binaryToDecimal(binaryStrin

48、g, low, high - 1) * 2+ (binaryString.charAt(high) -'0' );18.24import java.util.Scanner;public class Exercise18_24 public static void main(String args) Scanner input =new Scanner(System.in);System.out.print("Enter a hex number: ");String hex = input.nextLine();System.out.println(hex

49、 +" is decimal "+ hexToDecimal(hex);public static int hexToDecimal(String hexString) return hexToDecimal(hexString, 0, hexString.length() - 1);public static int hexToDecimal(String hexString,int low, int high) if (high < low)return 0;else return hexToDecimal(hexString, low, high - 1) *

50、16+ hexCharToDecimal(hexString.charAt(high);public static int hexCharToDecimal( char ch) if (ch >='A' && ch <='F' )return 10 + ch -'A' ;elsereturn ch -'018.25import java.util.Scanner;public class Exercise18_25 public static void main(String args) Scanner inp

51、ut =new Scanner(System.in);System.out.print("Enter a string: ");String s = input.nextLine();displayPermuation(s);public static void displayPermuation(String s) displayPermuation( "" , s);public static void displayPermuation(String s1, String s2) if (s2.length() > 0) for ( int

52、i = 0; i < s2.length(); i+) displayPermuation(s1 + s2.charAt(i), s2.substring(0, i) + s2.substring(i + 1);elseSystem.out.println(s1);18.26importjavafx.application.Application;importjavafx.geometry.Pos;importjavafx.scene.Scene;importjavafx.scene.control.Button;importjavafx.scene.control.Label;impo

53、rtjavafx.scene.layout.BorderPane;importjavafx.scene.layout.GridPane;importjavafx.scene.layout.HBox;importjavafx.scene.layout.StackPane;importjavafx.scene.paint.Color;importjavafx.scene.shape.Line;importjavafx.scene.shape.Rectangle;importjavafx.stage.Stage;publicclass Exercise18_26extends Application

54、 doublepaneWidth = 400;doublepaneHeight = 400;privateCell board =new Cell88;privateButton btFindPath =new Button( "Find Path"privateButton btClearPath =new Button( "Clear Path"privateLabel lblStatus =new Label();Override / Override the start method in the Application class public

55、 void start(Stage primaryStage) GridPane gridPane =new GridPane();for ( int i = 0; i < 8; i+) for ( int j = 0; j < 8; j+) gridPane.add(boardij =new Cell(), j, i);HBox hBox = new HBox(5);hBox.setAlignment(Pos.CENTER);hBox.getChildren().addAll(btFindPath, btClearPath);BorderPane pane = new Borde

56、rPane();pane.setTop(lblStatus);BorderPane.setAlignment(lblStatus, Pos.CENTER);pane.setCenter(gridPane);pane.setBottom(hBox);/ Create a scene and place it in the stageScene scene = new Scene(pane, paneWidth, paneHeight);primaryStage.setTitle("Exercise18_26" ); / Set the stage titleprimaryStage.setScene(scene);/ Place the scene in the stageprimaryStage.show();/ Display the stagebtFindPath.setOnAction(e -> findPath();btClearPath.s

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論