版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Java 语言程序设计(基础篇) (第 10 版 梁勇 著)第二十章 练习题答案20.1import java.util.*;import java.io.*;public class Exercise20_01 public static void main(String args) if (args.length != 1) System.out.println("Usage: java Exercise20_01 fullfilename" ); System.exit(1);String filename = args0;/ Create a list to hol
2、d the wordsArrayList<String> list = new ArrayList<String>();try Scanner in =new Scanner( new File(filename);String line;while (in.hasNext() line = in.nextLine(););String words = line.split( " ntr.,:?)("for (String word: words) "w+" )if (word.trim().length() > 0 &am
3、p;& word.trim().matches( list.add(word.trim();catch (Exception ex) System.err.println(ex);/ Get an iterator for the list Collections.sort(list);/ Display mappingsSystem.out.println( "nDisplay words in ascending order " for (String word: list) System.out.println(word);20.2import java.ut
4、il.Collections;import java.util.LinkedList;import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.control.ScrollPane;import javafx.scene.control.TextArea;import javafx.scene.c
5、ontrol.TextField;import javafx.scene.layout.BorderPane;import javafx.scene.layout.HBox;import javafx.stage.Stage;publicclass Exercise20_02extends Application privateLinkedList<Integer> list= new LinkedList<Integer>()privateTextField tfNumber =new TextField();privateTextArea taNumbers =ne
6、w TextArea();privateButton btSort =new Button( "Sort" );privateButton btShuffle =new Button( "Shuffle" );privateButton btReverse =new Button( "Reverse" );Override/ Override the start method in the Application classpublic void start(Stage primaryStage) HBox hBox =new HBo
7、x(10);BorderPane borderPane = borderPane.setTop(hBox); borderPane.setCenter(new BorderPane();new ScrollPane(taNumbers);HBox hBoxForButtons =new HBox(10););), tfNumber);hBox.getChildren().addAll( new Label( "Enter a number: " hBox.setAlignment(Pos.CENTER);hBoxForButtons.getChildren().addAll
8、(btSort, btShuffle, btReverse);hBoxForButtons.setAlignment(Pos.CENTER); borderPane.setBottom(hBoxForButtons);/ Create a scene and place it in the stageScene scene =new Scene(borderPane, 400, 210);primaryStage.setTitle( "Exercise20_02" ); / Set the stage title primaryStage.setScene(scene);
9、/ Place the scene in the stage primaryStage.show();/ Display the stagetfNumber.setOnAction(e -> if (!list.contains(new Integer(tfNumber.getText() taNumbers.appendText(tfNumber.getText() + " " ); list.add( new Integer(tfNumber.getText(););btSort.setOnAction(e -> Collections.sort(list)
10、;display(););btShuffle.setOnAction(e -> Collections.shuffle(list);display(););btReverse.setOnAction(e -> Collections.reverse(list); display(););private void display() taNumbers.setText( null );for (Integer i: list) taNumbers.appendText(i +" " );/* The main method is only needed for t
11、he IDE with limited* JavaFX support. Not needed for running from the command line. */ public static void main(String args) launch(args);20.3import java.util.*;public class Exercise20_03 public static void main(String args) String statecapital = "Alabama" ,"Montgomery" ,"Alas
12、ka" ,"Juneau" ,"Arizona" ,"Phoenix" ,"Arkansas", "Little Rock","California", "Sacramento","Colorado", "Denver" ,"Connecticut", "Hartford","Delaware", "Dover" ,"
13、Florida" ,"Tallahassee" ,"Georgia" ,"Atlanta" ,"Hawaii" ,"Honolulu" ,"Idaho" , "Boise" ,"Illinois", "Springfield","Maryland", "Annapolis" ,"Minnesota", "Saint Paul",
14、"Iowa" , "Des Moines" ,"Maine" , "Augusta" ,"Kentucky", "Frankfort" ,"Indiana" ,"Indianapolis","Kansas" ,"Topeka" ,"Louisiana", "Baton Rouge","Oregon" ,"Salem"
15、,"Oklahoma", "Oklahoma City","Ohio" , "Columbus" ,"North Dakota" , "Bismark","New York", "Albany" ,"New Mexico", "Santa Fe" ,"New Jersey", "Trenton" ,"New Hampshire" , &q
16、uot;Concord","Nevada" ,"Carson City" ,"Nebraska", "Lincoln" ,"Montana" ,"Helena" ,"Missouri", "Jefferson City","Mississippi", "Jackson" ,"Massachusettes" , "Boston" ,"Mic
17、higan" ,"Lansing" ,"Pennslyvania", "Harrisburg","Rhode Island", "Providence","South Carolina" , "Columbia","South Dakota", "Pierre" ,"Tennessee", "Nashville" ,"Texas" , "
18、Austin" ,"Utah" , "Salt Lake City","Vermont" ,"Montpelier" ,"Virginia" ,"Richmond" ,"Washington", "Olympia" ,"West Virginia", "Charleston","Wisconsin", "Madison" ,"Wyomin
19、g" ,"Cheyenne" ;List<String> list = Arrays.asList(statecapital); Collections.shuffle(list);int correctCount = 0;Scanner input =new Scanner(System.in);for ( int i = 0; i < list.size(); i+) / Prompt the user with a questionSystem.out.print("What is the capital of "+(S
20、tring)(list.get(i)0 + "? " );String capital = input.nextLine();if (capital.equals(String)(list.get(i)1) System.out.println("Your anwswer is correct");correctCount+;elseSystem.out.println("The correct answer should be "+ (String)(list.get(i)1);System.out.println("Th
21、e correct count is "+ correctCount);20.4import java.util.Arrays;/* This program works, but the design is not good. Redesign it */ public class Exercise20_04 / Each row in points represents a point private double points;public static void main(String args) Point points = new Point100;for ( int i
22、 = 0; i < points.length; i+) pointsi = new Point(Math.random() * 100, Math.random() * 100);System.out.println( "Sort on x-coordinates" ); Arrays.sort(points);for ( int i = 0; i < points.length; i+) System.out.println(pointsi);System.out.println("Sort on y-coordinates");Arra
23、ys.sort(points,new CompareY();for ( int i = 0; i < points.length; i+) System.out.println(pointsi);/* Define a class for a point with x- and y - coordinates */static class Point implements Comparable<Point> double x; double y;Point( double x, double y) this .x = x; this .y = y;Overridepublic
24、 int compareTo(Point p2) if ( this .x < p2.x)return -1;else if ( this .x = p2.x) / Secondary order on y-coordinates if ( this .y < p2.y) return -1;else if ( this .y = p2.y) return 0;else return 1; else return 1;Overridepublic String toString() return "(" + x + ", " + y + &q
25、uot;)" ;/* A comparator for comparing points on their y- coordinates. If y- coordinates * are the same, compare their x- coordinator.*/static class CompareY implements java.util.Comparator<Point> public int compare(Point p1, Point p2) if (p1.y < p2.y)return -1;else if (p1.y = p2.y) / S
26、econdary order on x-coordinatesif (p1.x < p2.x) return -1;else if (p1.x = p2.x) return 0;else return 1; elsereturn 1;20.5import java.util.List;import javafx.animation.KeyFrame;import javafx.animation.Timeline;import javafx.application.Application;import import import import import import import i
27、mport import import import import perty.DoubleProperty; javafx.geometry.Pos;javafx.scene.Node;javafx.stage.Stage; javafx.scene.Scene; javafx.scene.control.Button; javafx.scene.control.ScrollBar; javafx.scene.layout.BorderPane; javafx.scene.layout.HBox; javafx.scene.layout.Pane;
28、 javafx.scene.paint.Color; javafx.scene.shape.Circle;javafx.util.Duration;publicclass Exercise20_05 extends Application Override / Override the start method in the Application class public void start(Stage primaryStage) MultipleBallPane ballPane =new MultipleBallPane();ballPane.setStyle("-fx-bo
29、rder-color: yellow" );Button btSuspend = new Button( "Suspend" );Button btResume =new Button( "Resume" );Button btAdd = new Button( "+" );Button btSubtract = new Button( "-" );HBox hBox = new HBox(10); hBox.getChildren().addAll(btSuspend, btResume, btAdd,
30、 btSubtract); hBox.setAlignment(Pos.CENTER);/ Add or remove a ballbtAdd.setOnAction(e -> ballPane.add(); btSubtract.setOnAction(e -> ballPane.subtract();/ Pause and resume animation btSuspend.setOnAction(e -> ballPane.pause(); btResume.setOnAction(e -> ballPane.play();/ Use a scroll bar
31、to control animation speed ScrollBar sbSpeed = new ScrollBar(); sbSpeed.setMax(20);sbSpeed.setValue(10); ballPane.rateProperty().bind(sbSpeed.valueProperty();BorderPane pane = new BorderPane(); pane.setCenter(ballPane);pane.setTop(sbSpeed); pane.setBottom(hBox);/ Create a scene and place the pane in
32、 the stageScene scene = new Scene(pane, 350, 250);primaryStage.setTitle( "Exercise20_05" ); / Set the stage title primaryStage.setScene(scene); / Place the scene in the stage primaryStage.show(); / Display the stageprivate class MultipleBallPane extends Pane private Timeline animation;publ
33、ic MultipleBallPane() / Create an animation for moving the ballanimation = new Timeline(new KeyFrame(Dlis(50), e -> moveBall(); animation.setCycleCount(Timeline.INDEFINITE);animation.play();/ Start animationthis .setOnMousePressed(e -> List<Node> ballList = getChildren();for (
34、 int i = 0; i < ballList.size(); i+) if (ballList.get(i).contains(e.getX(), e.getY() ballList.remove(i);break ;);public void add() Color color =new Color(Math.random(),Math.random(), Math.random(), 0.5);getChildren().add(new Ball(30, 30, 5, color);public void subtract() if (getChildren().size() &
35、gt; 0) getChildren().remove(getChildren().size() - 1);public void play() animation.play();public void pause() animation.pause();public void increaseSpeed() animation.setRate(animation.getRate() + 0.1);public void decreaseSpeed() animation.setRate(animation.getRate() > 0 ? animation.getRate() - 0.
36、1 : 0);public DoubleProperty rateProperty() return animation.rateProperty();protected void moveBall() for (Node node: this .getChildren() Ball ball = (Ball)node;/ Check boundariesif (ball.getCenterX() < ball.getRadius() | ball.getCenterX() > getWidth() - ball.getRadius() ball.dx *= -1;/ Change
37、 ball move directionif (ball.getCenterY() < ball.getRadius() | ball.getCenterY() > getHeight() - ball.getRadius() ball.dy *= -1;/ Change ball move direction/ Adjust ball positionball.setCenterX(ball.dx + ball.getCenterX(); ball.setCenterY(ball.dy + ball.getCenterY();/ Detect collisionList<N
38、ode> ballList =this .getChildren();for ( int i = 0; i < ballList.size(); i+) for ( int j = i + 1; j < ballList.size(); j+) if (Ball)(ballList.get(i).isCollideWith(Ball)(ballList.get(j) / Change the radius for i(Ball)(ballList.get(i).setRadius( (Ball)ballList.get(i).getRadius() + (Ball)ballL
39、ist.get(j).getRadius();/ Remove jballList.remove(ballList.get(j);class Ball extends Circle private double dx = 1, dy = 1;Ball( double x, double y, double radius, Color color) super (x, y, radius);setFill(color);/ Set ball colorpublic boolean isCollideWith(Ball b) double distanceBetweenTheTwoBalls =
40、(Math.sqrt(Math.pow(getCenterX() - b.getCenterX(), 2) + Math.pow(getCenterY() - b.getCenterY(), 2);return distanceBetweenTheTwoBalls <= b.getRadius() + getRadius(); /* The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line.*/public st
41、atic void main(String args) launch(args);20.6import java.util.*;public class Exercise20_06 public static void main(String args) LinkedList<Integer> list =new LinkedList<Integer>();for ( int i = 0; i < 5000000; i+)list.add(i);long startTime = System.currentTimeMillis();for ( int i = 0;
42、 i < list.size(); i+)list.get(i);long endTime = System.currentTimeMillis();+ (endTime - startTime);" + (endTime - startTime);System.out.print("Travese time using index is "int x;startTime = System.currentTimeMillis();for ( int i: list) x = i;endTime = System.currentTimeMillis();Sys
43、tem.out.print( "Travese time using iterator is20.7import javafx.animation.KeyFrame;import javafx.animation.Timeline;import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.input.KeyCode;import javafx.scene.layout.Pane;import javafx.scene.paint.Color;import javafx.sce
44、ne.shape.Arc;import javafx.scene.shape.Line;import javafx.scene.shape.Circle;import javafx.scene.text.Text;import javafx.stage.Stage;import javafx.util.Duration;public class Exercise20_07 extends Application Override / Override the start method in the Application class public void start(Stage primar
45、yStage) HangmanPane pane = new HangmanPane();/ Create a scene and place it in the stageScene scene =new Scene(pane, 400, 250);primaryStage.setTitle( "Exercise20_07" ); / Set the stage title primaryStage.setScene(scene); / Place the scene in the stage primaryStage.show(); / Display the stag
46、epane.requestFocus();class HangmanPane extends Pane doubleballRadius = 10;doubleleftAngle = 120;doublerightAngle = 60;doubleangle = 90;/ Start from the middledoubleangleDelta = 1;/ Swing intervaldoubledelay = 100;Timeline animation = new Timeline( new KeyFrame(Dlis(200), e -> paint();p
47、ublic HangmanPane() animation.setCycleCount(Timeline.INDEFINITE);setNewHiddenWord();paint();this .setOnKeyPressed( e -> if (e.getCode() = KeyCode.ENTER) / Start a new game setNewHiddenWord(); else char letter = e.getText().charAt(0);System.out.println(letter); processAGuessedLetter(letter);if (nu
48、mberOfMisses = 7) animation.play();elseanimation.stop();paint(););protected void paint() this .getChildren().clear();if (isFinished) / Display the guessed wordthis .getChildren().add( guessedWord.toString();this .getChildren().add( ENTER"); else / Display the guessed word this .getChildren().ad
49、d( guessedWord.toString();newnewnewText(120, 210,"The word is: "Text(120, 230,Text(120, 210,"To continue the"Guess a word: "game, pressif (numberOfMisses > 0)this .getChildren().add(new Text(120, 230,"Missed letters: "missedLetters.toString();new Arc(60, 240, 40
50、, 20, 0, 180);arc.setFill(Color.WHITE); arc.setStroke(Color.BLACK);Arc arc =/ Draw the basenew Line(20 + 40, 220, 20 + 40, 20); new Line(20 + 40, 20, 20 + 40 + 100, 20);this .getChildren().addAll(arc, line1, line2);Line line1 =Line line2 =/ Draw the pole/ Draw the hangerif (numberOfMisses = 7) if (a
51、ngle < rightAngle)angleDelta = 1;/ Swing to the leftelse if (angle > leftAngle)angleDelta = -1; / Swing to the rightangle += angleDelta;return ; / Skip the restif (numberOfMisses < 1) double x1 = 20 + 40 + 100;double y1 = 20;double radius = 20;double x = x1 + radius * Math.cos(Math.toRadian
52、s(angle);double y = y1 + radius * Math.sin(Math.toRadians(angle);Line line3 =new Line(20 + 40 + 100, 20, x, y);/ Draw the hanger this .getChildren().add(line3);if (numberOfMisses < 2) return ; / Skip the rest/ Draw the circle double length = 20 + 20;x = x1 + (int ) (length * Math.cos(Math.toRadia
53、ns(angle);y = y1 + (int ) (length * Math.sin(Math.toRadians(angle);Circle circle = new Circle(x, y, radius); / Draw the hanger circle.setFill(Color.WHITE);circle.setStroke(Color.BLACK);this .getChildren().add(circle);if (numberOfMisses < 3) return ;/ Draw the left armlength = distance(x1, y1, 20
54、+ 40 + 100 - (int ) (radius * Math.cos(Math.toRadians(45), 40 + radius+ ( int ) (radius * Math.sin(Math.toRadians(45);double angle1 = Math.toDegrees(Math.asin(radius* Math.cos(Math.toRadians(45) / length);double x2 = x1 + ( int ) (length * Math.cos(Math.toRadians(angle + angle1);double y2 = y1 + ( i
55、nt ) (length * Math.sin(Math.toRadians(angle + angle1);length = (int ) distance(x1, y1, 20 + 40 + 100 - 60, 40 + radius + 60);angle1 = Math.toDegrees(Math.asin(60 / length);double x3 = x1 + ( int ) (length * Math.cos(Math.toRadians(angle + angle1);double y3 = y1 + ( int ) (length * Math.sin(Math.toR
56、adians(angle + angle1);Line line4 =new Line(x2, y2, x3, y3);this .getChildren().add(line4);if (numberOfMisses < 4) return ;/ Draw the right armlength = distance(x1, y1, 20 + 40 + 100 + (int ) (radius * Math.cos(Math.toRadians(45), 40 + radius+ ( int ) (radius * Math.sin(Math.toRadians(45);angle1
57、= -Math.toDegrees(Math.asin(radius * Math.cos(Math.toRadians(45)/ length);x2 = x1 + (y2 = y1 + (int ) (length * Math.cos(Math.toRadians(angle + angle1); int ) (length * Math.sin(Math.toRadians(angle + angle1);length = (int ) distance(x1, y1, 20 + 40 + 100 + 60, 40 + radius + 60);if (numberOfMisses &
58、lt; 5)return/ Draw the bodylength = 40 + 20; x2 = x1 + ( y2 = y1 + (int ) (length * Math.cos(Math.toRadians(angle); int ) (length * Math.sin(Math.toRadians(angle);length = 40 + 20 + 60;x3 = x1 + (int ) (length * Math.cos(Math.toRadians(angle);y3 = y1 + (int ) (length * Math.sin(Math.toRadians(angle)
59、;Line line6 =new Line(x2, y2, x3, y3);this .getChildren().add(line6);if (numberOfMisses < 6) return ;/ Draw the left leglength = distance(x1, y1, 20 + 40 + 100 - 40, 40 + radius + 80 + 40);angle1 = Math.toDegrees(Math.asin(40.0 / length);double x4 = x1 + ( int ) (length * Math.cos(Math.toRadians(angle + an
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 高中一年级道德与法治《我国的基本经济制度》课程
- 2026初中地理教资面试经典考题题库及解析
- 有关小学生周记范文集锦34篇
- 综合管理岗事业单位面试高频题题库及参考答案
- 奖罚管理制度28篇
- 2023年海南省上半年二级结构师皮带通廊砖砌体廊身应符合哪些要求考试试卷
- 高中地理湘教版五册知识清单编制与单元整体教学设计
- 初中八年级物理教学设计:滑动摩擦力影响因素的探究与建模
- 小学六年级班队活动《珍爱生命 远离毒品》教学设计
- 高中数学必修第一册《对数函数的图象与性质》教学设计
- GB/T 43683.6-2026水轮发电机组安装程序与公差导则第6部分:立式冲击式水轮机
- 央视网社会招聘考试题目目2026
- 钢筋混凝土排水管安装施工方案
- 高血压亚急症护理查房
- 2026年甘肃执法证考试题库及参考答案
- 成人留置导尿最佳实践指南解读
- 2025年三力测试最-全题库及答案
- 班会:运动安全记心间 - 运动会安全篇
- 医学26年:异常子宫出血诊疗 查房课件
- 2026年财务数智化转型升级白皮书
- 【答案】《固体废物处理与污染控制》(天津大学)章节期末慕课答案
评论
0/150
提交评论