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

《Java语言程序设计(基础篇)》(第10版梁勇著)第十六章练习题答案16.1import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.RadioButton;import javafx.scene.control.ToggleGroup;import yout.BorderPane;import yout.HBox;import yout.Pane;import javafx.scene.paint.Color;import javafx.scene.text.Font;import javafx.scene.text.Text;import javafx.stage.Stage;public class Exercise16_01 extends Application {private double paneWidth = 500;private double paneHeight = 150;@Override // Override the start method in the Application class public void start(Stage primaryStage) {Text text = new Text(20, 40, "Programming is fun");text.setFont(new Font("Times", 20));Pane paneForText = new Pane();paneForText.getChildren().add(text);paneForText.setStyle("-fx-border-color: gray");RadioButton rbRed = new RadioButton("Red");RadioButton rbYellow = new RadioButton("Yellow");RadioButton rbBlack = new RadioButton("Black");RadioButton rbOrange = new RadioButton("Orange");RadioButton rbGreen = new RadioButton("Green");ToggleGroup group = new ToggleGroup();rbRed.setToggleGroup(group);rbYellow.setToggleGroup(group);rbBlack.setToggleGroup(group);rbBlack.setSelected(true);rbOrange.setToggleGroup(group);rbGreen.setToggleGroup(group);HBox hBox = new HBox(5);hBox.getChildren().addAll(rbRed, rbYellow, rbBlack, rbOrange, rbGreen); hBox.setAlignment(Pos.CENTER);Button btLeft = new Button("<=");Button btRight = new Button("=>");HBox hBoxForButtons = new HBox(5);hBoxForButtons.getChildren().addAll(btLeft, btRight);hBoxForButtons.setAlignment(Pos.CENTER);BorderPane borderPane = new BorderPane();borderPane.setTop(hBox);borderPane.setCenter(paneForText);borderPane.setBottom(hBoxForButtons);// Create a scene and place it in the stageScene scene = new Scene(borderPane, paneWidth, paneHeight + 40);primaryStage.setTitle("Exercise16_01"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagerbRed.setOnAction(e -> text.setStroke(Color.RED));rbYellow.setOnAction(e -> text.setStroke(Color.YELLOW));rbBlack.setOnAction(e -> text.setStroke(Color.BLACK));rbOrange.setOnAction(e -> text.setStroke(Color.ORANGE));rbGreen.setOnAction(e -> text.setStroke(Color.GREEN));btLeft.setOnAction(e -> text.setX(text.getX() - 1));btRight.setOnAction(e -> text.setX(text.getX() + 1));}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}16.1附加import javafx.application.Application;import javafx.scene.Scene;import yout.*;import javafx.scene.paint.Color;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.geometry.Pos;public class Exercise16_01Extra extends Application {final static double PANEL_WIDTH = 400;final static double PANEL_HEIGHT = 140;@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {GridPane paneForOriginal = new GridPane();GridPane paneForInversed = new GridPane();TextField[][] tfOriginal = new TextField[3][3];TextField[][] tfInversed = new TextField[3][3];for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {paneForOriginal.add(tfOriginal[i][j] = new TextField(), j, i); tfOriginal[i][j].setPrefColumnCount(4);paneForInversed.add(tfInversed[i][j] = new TextField(), j, i); tfInversed[i][j].setPrefColumnCount(4);}}BorderPane p1 = new BorderPane();p1.setCenter(paneForOriginal);p1.setTop(new Label("Original Matrix"));BorderPane p2 = new BorderPane();p2.setCenter(paneForInversed);final Label lblStatus = new Label("Inversed Matrix");p2.setTop(lblStatus);HBox hBox = new HBox(5);hBox.getChildren().addAll(p1, p2);BorderPane pane = new BorderPane();pane.setCenter(hBox);Button btGetInverse = new Button("Get Inverse");pane.setBottom(btGetInverse);BorderPane.setAlignment(btGetInverse, Pos.CENTER);Scene scene = new Scene(pane, PANEL_WIDTH, PANEL_HEIGHT);primaryStage.setTitle("Exercise16_01"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagebtGetInverse.setOnAction(e -> {double[][] A = new double[3][3];for (int i = 0; i < 3; i++)for (int j = 0; j < 3; j++) {A[i][j] = Double.parseDouble(tfOriginal[i][j].getText()); }double[][] inverseA = Exercise08_03Extra.inverse(A);if (inverseA == null)lblStatus.setText("Invered matrix: No inverse matrix");else {for (int i = 0; i < 3; i++)for (int j = 0; j < 3; j++) {tfInversed[i][j].setText(inverseA[i][j] + "");}}});}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16.2import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.CheckBox;import javafx.scene.control.RadioButton;import javafx.scene.control.ToggleGroup;import yout.BorderPane;import yout.HBox;import yout.StackPane;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.shape.Ellipse;import javafx.scene.shape.Rectangle;import javafx.stage.Stage;public class Exercise16_02 extends Application {private double paneWidth = 500;private double paneHeight = 150;@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {StackPane pane = new StackPane();Circle circle = new Circle(20, 20, 50);circle.setStroke(Color.BLACK);circle.setFill(Color.WHITE);Rectangle rectangle = new Rectangle(20, 20, 80, 50);rectangle.setStroke(Color.BLACK);Ellipse ellipse = new Ellipse(20, 20, 50, 70);ellipse.setStroke(Color.BLACK);pane.setStyle("-fx-border-color: gray");pane.getChildren().add(circle);RadioButton rbCircle = new RadioButton("Circle");RadioButton rbRectangle = new RadioButton("Rectangle");RadioButton rbEllipse = new RadioButton("Ellipse");CheckBox chkFill = new CheckBox("Fill");ToggleGroup group = new ToggleGroup();rbCircle.setToggleGroup(group);rbCircle.setSelected(true);rbRectangle.setToggleGroup(group);rbEllipse.setToggleGroup(group);HBox hBox = new HBox(5);hBox.getChildren().addAll(rbCircle, rbRectangle, rbEllipse, chkFill); hBox.setAlignment(Pos.CENTER);BorderPane borderPane = new BorderPane();borderPane.setCenter(pane);borderPane.setBottom(hBox);// Create a scene and place it in the stageScene scene = new Scene(borderPane, paneWidth, paneHeight + 40); primaryStage.setTitle("Exercise16_02"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagerbCircle.setOnAction(e -> {pane.getChildren().clear();pane.getChildren().add(circle);if (chkFill.isSelected()) {circle.setFill(Color.BLACK);}else {circle.setFill(Color.WHITE);}});rbRectangle.setOnAction(e -> {pane.getChildren().clear();pane.getChildren().add(rectangle);if (chkFill.isSelected()) {rectangle.setFill(Color.BLACK);}else {rectangle.setFill(Color.WHITE);}});rbEllipse.setOnAction(e -> {pane.getChildren().clear();pane.getChildren().add(ellipse);if (chkFill.isSelected()) {ellipse.setFill(Color.BLACK);}else {ellipse.setFill(Color.WHITE);}});chkFill.setOnAction(e -> {if (chkFill.isSelected()) {circle.setFill(Color.BLACK);rectangle.setFill(Color.BLACK);ellipse.setFill(Color.BLACK);}else {circle.setFill(Color.WHITE);rectangle.setFill(Color.WHITE);ellipse.setFill(Color.WHITE);}});}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16.2附加import javafx.application.Application;import javafx.scene.Scene;import yout.*;import javafx.scene.paint.Color;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.geometry.Pos;public class Exercise16_02Extra extends Application {final static double PANEL_WIDTH = 400;final static double PANEL_HEIGHT = 140;@Override // Override the start method in the Application class public void start(Stage primaryStage) {GridPane paneForOriginal = new GridPane();GridPane paneForInversed = new GridPane();TextField[][] tfA = new TextField[3][3];TextField[] tfB = new TextField[3];for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {tfA[i][j] = new TextField();tfA[i][j].setPrefColumnCount(4);}tfB[i] = new TextField();tfB[i].setPrefColumnCount(4);}HBox[] hBoxes = new HBox[3];for (int i = 0; i < 3; i++) {hBoxes[i] = new HBox(5);hBoxes[i].getChildren().addAll(tfA[i][0], new Label("x"), tfA[i][1], new Label("y"), tfA[i][2], new Label("z = "), tfB[i]);}VBox vBox = new VBox(5);vBox.getChildren().addAll(hBoxes[0], hBoxes[1], hBoxes[2]);HBox hBox = new HBox(5);Label lblStatus = new Label();Button btSolveEquation = new Button("Solve Equation");hBox.getChildren().addAll(btSolveEquation, lblStatus);BorderPane pane = new BorderPane();pane.setCenter(vBox);pane.setBottom(hBox);Scene scene = new Scene(pane, PANEL_WIDTH, PANEL_HEIGHT);primaryStage.setTitle("Exercise16_02"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagebtSolveEquation.setOnAction(e -> {double[][] A = new double[3][3];double[] B = new double[3];for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {A[i][j] = Double.parseDouble(tfA[i][j].getText());}B[i] = Double.parseDouble(tfB[i].getText());}double[] result = Exercise08_02Extra.getSolution(A, B);if (result == null)lblStatus.setText("No solutions");elselblStatus.setText("Solution is x = "+ result[0] + ", y is = "+ result[1]+ ", and z is = " + result[2]);});}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16.3import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.RadioButton;import javafx.scene.control.ToggleGroup;import yout.BorderPane;import yout.HBox;import yout.Pane;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.shape.Rectangle;import javafx.stage.Stage;public class Exercise16_03 extends Application {private double paneWidth = 200;private double paneHeight = 90;@Override // Override the start method in the Application class public void start(Stage primaryStage) {Pane pane = new Pane();Circle circleRed = new Circle(paneWidth / 2, 20, 10);Circle circleYellow = new Circle(paneWidth / 2, 50, 10);Circle circleGreen = new Circle(paneWidth / 2, 80, 10);circleRed.setStroke(Color.BLACK);circleYellow.setStroke(Color.BLACK);circleGreen.setStroke(Color.BLACK);circleRed.setFill(Color.WHITE);circleYellow.setFill(Color.WHITE);circleGreen.setFill(Color.WHITE);Rectangle rectangle = new Rectangle(paneWidth / 2 - 15, 5, 30, 90); rectangle.setFill(Color.WHITE);rectangle.setStroke(Color.BLACK);pane.getChildren().addAll(rectangle, circleRed, circleYellow, circleGreen);RadioButton rbRed = new RadioButton("Red");RadioButton rbYellow = new RadioButton("Yellow");RadioButton rbGreen = new RadioButton("Green");ToggleGroup group = new ToggleGroup();rbRed.setToggleGroup(group);rbYellow.setToggleGroup(group);rbGreen.setToggleGroup(group);HBox hBox = new HBox(5);hBox.getChildren().addAll(rbRed, rbYellow, rbGreen);hBox.setAlignment(Pos.CENTER);BorderPane borderPane = new BorderPane();borderPane.setCenter(pane);borderPane.setBottom(hBox);// Create a scene and place it in the stageScene scene = new Scene(borderPane, paneWidth, paneHeight + 40);primaryStage.setTitle("Exercise16_03"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagerbRed.setOnAction(e -> {circleRed.setFill(Color.RED);circleYellow.setFill(Color.WHITE);circleGreen.setFill(Color.WHITE);});rbYellow.setOnAction(e -> {circleYellow.setFill(Color.YELLOW);circleRed.setFill(Color.WHITE);circleGreen.setFill(Color.WHITE);});rbGreen.setOnAction(e -> {circleGreen.setFill(Color.GREEN);circleYellow.setFill(Color.WHITE);circleRed.setFill(Color.WHITE);});}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}16.3附加import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import yout.*;import javafx.scene.paint.Color;import javafx.scene.control.*;import javafx.scene.shape.Rectangle;import javafx.stage.Stage;public class Exercise16_03Extra extends Application {@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {HBox hBox = new HBox(5);TextField tfRed = new TextField();tfRed.setPrefColumnCount(4);TextField tfBlue = new TextField();tfBlue.setPrefColumnCount(4);TextField tfGreen = new TextField();tfGreen.setPrefColumnCount(4);hBox.getChildren().addAll(new Label("Red"), tfRed, new Label("Blue"), tfBlue, new Label("Green"), tfGreen);hBox.setAlignment(Pos.CENTER);BorderPane pane = new BorderPane();MandelbrotCanvas canvas = new MandelbrotCanvas();pane.setCenter(canvas);pane.setBottom(hBox);// Create a scene and place it in the stageScene scene = new Scene(pane, 425, 450);primaryStage.setTitle("Exercise16_03"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagetfRed.setOnAction(e -> {canvas.setRed(Integer.parseInt(tfRed.getText()));canvas.paint();});tfBlue.setOnAction(e -> {canvas.setBlue(Integer.parseInt(tfBlue.getText()));canvas.paint();});tfGreen.setOnAction(e -> {canvas.setGreen(Integer.parseInt(tfGreen.getText()));canvas.paint();});}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}class MandelbrotCanvas extends Pane {final static int COUNT_LIMIT = 60;MandelbrotCanvas() {paint();}private void paint() {this.getChildren().clear();for (double x = -2.0; x < 2.0; x += 0.01)for (double y = -2.0; y < 2.0; y += 0.01) {Rectangle rectangle = new Rectangle(x * 100 + 200, y * 100 + 200, 1.0, 1.0);this.getChildren().add(rectangle); // Fill the rectangle with the specified colorint c = count(new Complex(x, y));if (c == COUNT_LIMIT)rectangle.setFill(Color.BLACK); // c is in a Mandelbrot set elserectangle.setFill(Color.rgb(c * red % 256, c * blue % 256, c * green % 256));}}int red = 77;int blue = 58;int green = 159;public void setRed(int red) {this.red = red;}public void setBlue(int blue) {this.blue = blue;}public void setGreen(int green) {this.green = green;}/** Returns the iteration count */int count(Complex c) {Complex z = new Complex(0, 0); // z0for (int i = 0; i < COUNT_LIMIT; i++) {z = z.multiply(z).add(c); // Get z1, z2, ...if (z.abs() > 2) return i; // The sequence is unbounded}return COUNT_LIMIT; // Indicates a bounded sequence}}}16.4import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import bel;import javafx.scene.control.TextField;import yout.GridPane;import javafx.stage.Stage;public class Exercise16_04 extends Application {private double paneWidth = 250;private double paneHeight = 60;@Override // Override the start method in the Application class public void start(Stage primaryStage) {TextField tfMile = new TextField();TextField tfKilometer = new TextField();tfMile.setAlignment(Pos.BOTTOM_RIGHT);tfKilometer.setAlignment(Pos.BOTTOM_RIGHT);GridPane pane = new GridPane();pane.setAlignment(Pos.CENTER);pane.add(new Label("Mile"), 0, 0);pane.add(tfMile, 1, 0);pane.add(new Label("Kilometer"), 0, 1);pane.add(tfKilometer, 1, 1);// Create a scene and place it in the stageScene scene = new Scene(pane, paneWidth, paneHeight);primaryStage.setTitle("Exercise16_04"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagetfMile.setOnAction(e -> {double mile = new Double(tfMile.getText().trim()).doubleValue();double kilometer = mile / 0.6241;tfKilometer.setText(new Double(kilometer).toString());});tfKilometer.setOnAction(e -> {double kilometer = newDouble(tfKilometer.getText().trim()).doubleValue();double mile = 0.6241 * kilometer;tfMile.setText(new Double(mile).toString());});}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16.4附加import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.*;import yout.*;import javafx.stage.Stage;public class Exercise16_04Extra extends Application {private double paneWidth = 520;private double paneHeight = 240;private String singleFilerScheme ="Single Filers\nTaxable Income\t\tRate\n" +"Up to $27,050\t\t15%\n"+"$27,051 - $65,550\t27.5%\n" +"$65,551 - $136,750\t30.5%\n" +"$136,751 - $297,350\t35.5%\n" +"$297,351 or more\t39.1%";private String marriedJointlyFilerScheme ="Married Jointly Fliers\nTaxable Income\t\tRate\n" +"Up to $45,200\t\t15%\n"+"$45,201 - $109,250\t27.5%\n" +"$109,251 - $166,500\t30.5%\n" +"$166,501 - $297,350\t35.5%\n" +"$297,351 or more\t39.1%";private String marriedSeparatelyFilerScheme ="Married Separately Fliers\nTaxable Income\t\tRate\n" +"Up to $22,600\t\t15%\n"+"$22,601 - $54,655\t27.5%\n" +"$54,656 - $83,250\t30.5%\n" +"$83,251 - $148,675\t35.5%\n" +"$148,676 or more\t39.1%";private String headOfHouseFilerScheme ="Head of Household Fliers\nTaxable Income\t\tRate\n" +"Up to $36,250\t\t15%\n"+"$36,251 - $93,650\t27.5%\n" +"$93,651 - $151,650\t30.5%\n" +"$151,651 - $297,350\t35.5%\n" +"$297,351 or more\t39.1%";@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {RadioButton singleFiler = new RadioButton("Single filers");singleFiler.setSelected(true);RadioButton marriedJointly = new RadioButton("Married filing jointly or qualifying widow(er)");RadioButton marriedSeparately = new RadioButton("Married filing separately");RadioButton headOfHousehold = new RadioButton("Head of Household");ToggleGroup group = new ToggleGroup();singleFiler.setToggleGroup(group);marriedJointly.setToggleGroup(group);marriedSeparately.setToggleGroup(group);headOfHousehold.setToggleGroup(group);VBox vBox = new VBox(5);vBox.getChildren().addAll(singleFiler, marriedJointly, marriedSeparately,headOfHousehold);HBox hBox = new HBox(5);Label lblDescription = new Label(singleFilerScheme);hBox.getChildren().addAll(vBox, lblDescription);GridPane pane = new GridPane();pane.setHgap(5);pane.setVgap(5);TextField tfTaxableIncome = new TextField();TextField tfTax = new TextField();tfTaxableIncome.setPrefColumnCount(8);tfTax.setPrefColumnCount(8);tfTax.setEditable(false);pane.setAlignment(Pos.CENTER);pane.add(new Label("Taxable income"), 0, 0);pane.add(tfTaxableIncome, 1, 0);pane.add(new Label("Tax"), 0, 1);pane.add(tfTax, 1, 1);Button btComputeTax = new Button("Compute Tax");pane.add(btComputeTax, 1, 2);VBox vBoxAll = new VBox(5);vBoxAll.getChildren().addAll(new Label("Select Tax Status"), hBox, pane);// Create a scene and place it in the stageScene scene = new Scene(vBoxAll, paneWidth, paneHeight);primaryStage.setTitle("Exercise16_04"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagesingleFiler.setOnAction(e -> lblDescription.setText(singleFilerScheme)); marriedJointly.setOnAction(e ->lblDescription.setText(marriedJointlyFilerScheme));marriedSeparately.setOnAction(e ->lblDescription.setText(marriedSeparatelyFilerScheme));headOfHousehold.setOnAction(e ->lblDescription.setText(headOfHouseFilerScheme));btComputeTax.setOnAction(e -> {Tax tax = new Tax(); // Programming Exercise 10.8int status = 0;if (singleFiler.isSelected())status = 0;else if (marriedJointly.isSelected())status = 1;else if (marriedSeparately.isSelected())status = 2;else if (headOfHousehold.isSelected())status = 3;tax.setFilingStatus(status);tax.setTaxableIncome(Double.parseDouble(tfTaxableIncome.getText() + ""));tfTax.setText(tax.findTax() + "");});}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16.5import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import bel;import javafx.scene.control.TextField;import yout.GridPane;import javafx.stage.Stage;public class Exercise16_05 extends Application {private double paneWidth = 250;private double paneHeight = 90;@Override // Override the start method in the Application class public void start(Stage primaryStage) {TextField tfDecimal = new TextField();TextField tfHex = new TextField();TextField tfBinary = new TextField();tfDecimal.setAlignment(Pos.BOTTOM_RIGHT);tfHex.setAlignment(Pos.BOTTOM_RIGHT);tfBinary.setAlignment(Pos.BOTTOM_RIGHT);tfHex.setAlignment(Pos.BOTTOM_RIGHT);GridPane pane = new GridPane();pane.setAlignment(Pos.CENTER);pane.setHgap(10);pane.add(new Label("Decimal"), 0, 0);pane.add(tfDecimal, 1, 0);pane.add(new Label("Hex"), 0, 1);pane.add(tfHex, 1, 1);pane.add(new Label("Binary"), 0, 2);pane.add(tfBinary, 1, 2);// Create a scene and place it in the stageScene scene = new Scene(pane, paneWidth, paneHeight);primaryStage.setTitle("Exercise16_05"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stagetfDecimal.setOnAction(e -> {int decimal = Integer.parseInt(tfDecimal.getText());tfHex.setText(Integer.toHexString(decimal));tfBinary.setText(Integer.toBinaryString(decimal));});tfHex.setOnAction(e -> {int decimal = Integer.parseInt(tfHex.getText(), 16);tfDecimal.setText(decimal + "");tfBinary.setText(Integer.toBinaryString(decimal));});tfBinary.setOnAction(e -> {int decimal = Integer.parseInt(tfBinary.getText(), 2);tfDecimal.setText(decimal + "");tfHex.setText(Integer.toHexString(decimal));});}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16.5附加import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.*;import yout.*;import javafx.stage.Stage;public class Exercise16_05Extra extends Application {private double paneWidth = 240;private double paneHeight = 200;private Button bt1 = new Button("1");private Button bt2 = new Button("2");private Button bt3 = new Button("3");private Button bt4 = new Button("4");private Button bt5 = new Button("5");private Button bt6 = new Button("6");private Button bt7 = new Button("7");private Button bt8 = new Button("8");private Button bt9 = new Button("9");private Button bt0 = new Button("0");private Button btAdd = new Button("+");private Button btSubtract = new Button("-");private Button btMultiply = new Button("*");private Button btDivide = new Button("/");private Button btRemainder = new Button("%");private Button btSqrt = new Button("sqrt");private Button btDecimal = new Button(".");private Button btEqual = new Button("=");private TextField tf = new TextField();@Override // Override the start method in the Application class public void start(Stage primaryStage) {GridPane pane = new GridPane();pane.setHgap(5);pane.setVgap(5);pane.add(new Button("MC"), 0, 0);pane.add(bt7, 1, 0);pane.add(bt8, 2, 0);pane.add(bt9, 3, 0);pane.add(btDivide, 4, 0);pane.add(btSqrt, 5, 0);pane.add(new Button("MR"), 0, 1);pane.add(bt4, 1, 1);pane.add(bt5, 2, 1);pane.add(bt6, 3, 1);pane.add(btMultiply, 4, 1);pane.add(btRemainder, 5, 1);pane.add(new Button("MS"), 0, 2);pane.add(bt1, 1, 2);pane.add(bt2, 2, 2);pane.add(bt3, 3, 2);pane.add(btSubtract, 4, 2);pane.add(new Button("1/x"), 5, 2);pane.add(new Button("M+"), 0, 3);pane.add(bt0, 1, 3);pane.add(new Button("+/-"), 2, 3);pane.add(btDecimal, 3, 3);pane.add(btAdd, 4, 3);pane.add(btEqual, 5, 3);HBox hBox = new HBox(5);hBox.getChildren().addAll(new Button("Back"), new Button("CE"), new Button("C"));hBox.setAlignment(Pos.BASELINE_RIGHT);VBox vBox = new VBox(5);vBox.getChildren().addAll(tf, hBox, pane);// Create a scene and place it in the stageScene scene = new Scene(vBox, paneWidth, paneHeight);primaryStage.setTitle("Exercise16_05"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stage}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16.6import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import bel;import javafx.scene.control.RadioButton;import javafx.scene.control.TextField;。

合集下载

梁勇java第十版复习题答案

梁勇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;}}。

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

Java语言程序设计基础篇全习题答案16

Chapter 16 Applets and Multimedia1. Every applet is an instance of java.awt.Applet. Not every applet is an instance ofjavax.swing.JApplet. Only the Swing applets are instances of JApplet.2. See the section "The Applet Class."3. The components are added to the content pane of the applets. The default layoutmanager of the content pane of JApplet is BorderLayout.4. (a) The void should be removed to declare a constructor.(b) The jlblMessage is declared in Line 2 as a data field, but redeclared in Line 5as a local variable. The local variable is assigned with new JLabel("It is Java"),but the data field is still null. In Line 12, jlblMessage is null, which causesNullPointerException.5. See the section "The <applet> HTML Tag." You use the <param> tag to passparameters to an applet.getParameter() method is defined in the Applet class.6. The7. Revision 1 is wrong because the getParameter method is an instance method andit cannot be invoked before an instance of the applet is created. Revision 2 iswrong because the init method is invoked after the applet instance is created.8.An application has a main() method and runs as astandalone. An applet does not need a main method andmust run from a Web browser. Applications and applets arecompiled in the same way.Applets are not allowed to read from, or write to, the file system of the computer.Applets are not allowed to run any programs on the browser's computer. Appletsare not allowed to establish connections between the user's computer and anothercomputer except with the server where the applets are stored.9. No.10. Yes. You can create an instance of JApplet and place it in a frame and use it.11. You will see garbage displayed in the cell.12. To create an URL object for the file /liang/anthem/us.mid on theInternet, use new URL(“/liang/anthem/us.mid”). To create anURL object for the file anthem/us.mid, useURL url = this.getClass().getResource(filename);13. First create an URL for the image source, then use new ImageIcon(url) to createan ImageIcon for the source.14. You can use AIFF, MIDI, and RMF in addition to AU and WAS files in Java 2.15. First create an URL for the audio source, then use the Applet.getAudioClip(url)method to obtain an audio clip.16. You can use the play(), stop(), and loop() methods to play, stop, orrepeatedly play the audio, respectively.。

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语言程序设计(基础篇)原书第十版梁勇著第一章答案

第一章1.1 public class Test{public static void main(String[] args){System.out.println("Welcome to Java !");System.out.println("Welcome to Computer Science !");System.out.println("Programming is fun .");}}1.2 public class Test{public static void main(String[] args){for(int i = 0;i <= 4;i++){System.out.println("Welcome to Java !");}}}1.3 public class Test{public static void main(String[] args){System.out.println(" ]");System.out.println(" ]");System.out.println("] ]");System.out.println(" ]]");}}public class Test{public static void main(String[] args){System.out.println(" A");System.out.println(" A A");System.out.println(" AAAAA");System.out.println("A A");}}public class Test{public static void main(String[] args){System.out.println("V V");System.out.println(" V V");System.out.println(" V V");System.out.println(" V");}}1.4 public class Test{public static void main(String[] args){System.out.println("a a^2 a^3");System.out.println("1 1 1");System.out.println("2 4 8");System.out.println("3 9 27");System.out.println("4 16 64");}}1.5 public class Test{public static void main(String[] args){System.out.println((9.5*4.5-2.5*3)/(45.5-3.5));}}1.6 public class Test{public static void main(String[] args){int i = 1,sum = 0;for(;i <= 9;i++)sum += i;System.out.println(sum);}}1.7 public class Test{public static void main(String[] args){System.out.println(4*(1.0-1.0/3+1.0/5-1.0/7+1.0/9-1.0/11));System.out.println(4*(1.0-1.0/3+1.0/5-1.0/7+1.0/9-1.0/11+1.0/13)) ;}}1.8 public class Test{public static void main(String[] args){final double PI = 3.14;double radius = 5.5;System.out.println(2 * radius * PI);System.out.println(PI * radius * radius);}}1.9 public class Test{public static void main(String[] args){System.out.println(7.9 * 4.5);System.out.println(2 * (7.9 + 4.5));}}1.10 public class Test{public static void main(String[] args){double S = 14 / 1.6;double T = 45 * 60 + 30;double speed = S / T;System.out.println(speed);}}1.11public class Test{public static void main(String[] args){int BN = 312032486; //original person numbersdouble EveryYS,EveryYBP,EveryYDP,EveryYMP;EveryYS = 365 * 24 * 60 * 60;EveryYBP = EveryYS / 7;EveryYDP = EveryYS / 13;EveryYMP = EveryYS / 45;int FirstYP,SecondYP,ThirdYP,FourthYP,FivthYP;FirstYP = (int)(BN + EveryYBP + EveryYMP - EveryYDP);SecondYP = (int)(FirstYP + EveryYBP + EveryYMP - EveryYDP);ThirdYP = (int)(SecondYP + EveryYBP + EveryYMP - EveryYDP);FourthYP = (int)(ThirdYP + EveryYBP + EveryYMP - EveryYDP);FivthYP = (int)(FourthYP + EveryYBP + EveryYMP - EveryYDP);System.out.println(FirstYP);System.out.println(SecondYP);System.out.println(ThirdYP);System.out.println(FourthYP);System.out.println(FivthYP);}}1.12 public class Test{public static void main(String[] args){double S = 24 * 1.6;double T = (1 * 60 + 40) * 60 + 35;double speed = S / T;System.out.println(speed);}}1.13 import java.util.Scanner;public class Test{public static void main(String[] args){Scanner input = new Scanner(System.in);System.out.println("input a,b,c,d,e,f value please:");double a = input.nextDouble();double b = input.nextDouble();double c = input.nextDouble();double d = input.nextDouble();double e = input.nextDouble();double f = input.nextDouble();double x,y;x = (e * d - b * f) / (a * d - b * c);y = (a * f - e * c) / (a * d - b * c);System.out.println("The result is x: "+(int)(x * 1000) / 1000.0);System.out.println("The result is y: "+(int)(y * 1000) / 1000.0);}}。

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Map接口用于存储键值对。

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

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

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

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

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

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

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

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

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