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

《Java语言程序设计(基础篇)》(第10版梁勇著)第二十九章练习题答案29.3/** Solution provided by N鎠je Frode, April 2013 */public class Exercise29_03 {public static void main(String[] args) {int [][] edges = new int[][]{{0, 1, 2}, {0, 3, 8},{1, 0, 2}, {1, 2, 7}, {1, 3, 3},{2, 1, 7}, {2, 3, 4}, {2, 4, 5},{3, 0, 8}, {3, 1, 3}, {3, 2, 4}, {3, 4, 6},{4, 2, 5}, {4, 3, 6}};Integer[][] adjacencyMatrix = {{null, 2,null, 8,null},{ 2,null, 7, 3,null},{null, 7,null, 4, 5},{ 8, 3, 4,null, 6},{null,null, 5, 6,null}};System.out.println("\nSolution with adjacency matrix:");WeightedGraphAdj<Integer> graph = new WeightedGraphAdj<>(edges, 5); WeightedGraphAdj<Integer>.ShortestPathTree tree =graph.getShortestPathAdj(3, adjacencyMatrix);tree.printAllPaths();}}29.4\import java.util.ArrayList;import java.util.List;import java.util.Scanner;public class Exercise29_04 {public static void main(String[] args) {new Exercise29_04();}public Exercise29_04() {// Prompt the user to enter nine coins H抯 and T'sSystem.out.print("Enter an initial nine coin H抯 and T's: ");Scanner input = new Scanner(System.in);String s = input.nextLine();char[] initialNode = s.toCharArray();ModifiedWeightedNineTailModel model = new ModifiedWeightedNineTailModel();java.util.List<Integer> path =model.getShortestPath(NineTailModel.getIndex(initialNode));System.out.println("The steps to flip the coins are ");for (int i = 0; i < path.size(); i++)NineTailModel.printNode(NineTailModel.getNode(path.get(i).intValue()));System.out.println("The number of flips is " +model.getNumberOfFlips(NineTailModel.getIndex(initialNode)));}public static class ModifiedWeightedNineTailModel extends NineTailModel { /** Construct a model */public ModifiedWeightedNineTailModel() {// Create edgesList<WeightedEdge> edges = getEdges();// Create a graphWeightedGraph<Integer> graph = new WeightedGraph<Integer>(edges, NUMBER_OF_NODES);// Obtain a BSF tree rooted at the target nodetree = graph.getShortestPath(511);}/** Create all edges for the graph */private List<WeightedEdge> getEdges() {// Store edgesList<WeightedEdge> edges = new ArrayList<WeightedEdge>();for (int u = 0; u < NUMBER_OF_NODES; u++) {for (int k = 0; k < 9; k++) {char[] node = getNode(u); // Get the node for vertex uif (node[k] == 'H') {int v = getFlippedNode(node, k);int numberOfFlips = getNumberOfFlips(u, v);// Add edge (v, u) for a legal move from node u to node v edges.add(new WeightedEdge(v, u, numberOfFlips));}}}return edges;}private static int getNumberOfFlips(int u, int v) {char[] node1 = getNode(u);char[] node2 = getNode(v);int count = 0; // Count the number of different cellsfor (int i = 0; i < node1.length; i++)if (node1[i] != node2[i]) count++;return 3 * count;}public int getNumberOfFlips(int u) {return (int)((WeightedGraph<Integer>.ShortestPathTree)tree).getCost(u);}}}29.5import java.util.ArrayList;import java.util.List;public class Exercise29_05 {public static void main(String[] args) {NineTailModel model1 = new NineTailModel();WeightedNineTailModel model2 = new WeightedNineTailModel();AbstractGraph.Tree tree1 = model1.tree;AbstractGraph.Tree tree2 = model2.tree;for (int i = 0; i < 511; i++) {// System.out.println(tree1.depth(i));if (depth(tree1, i) != depth(tree2, i))System.out.println(i);}System.out.println("Finished");}private static int depth(AbstractGraph.Tree tree, int v) {return tree.getPath(v).size();}public static class ModifiedWeightedNineTailModel extends NineTailModel { /** Construct a model */public ModifiedWeightedNineTailModel() {// Create edgesList<WeightedEdge> edges = getEdges();// Create a graphWeightedGraph<Integer> graph = new WeightedGraph<Integer>(edges, NUMBER_OF_NODES);// Obtain a BSF tree rooted at the target nodetree = graph.getShortestPath(511);}/** Create all edges for the graph */private List<WeightedEdge> getEdges() {// Store edgesList<WeightedEdge> edges = new ArrayList<WeightedEdge>();for (int u = 0; u < NUMBER_OF_NODES; u++) {for (int k = 0; k < 9; k++) {char[] node = getNode(u); // Get the node for vertex uif (node[k] == 'H') {int v = getFlippedNode(node, k);int numberOfFlips = getNumberOfFlips(u, v);// Add edge (v, u) for a legal move from node u to node vedges.add(new WeightedEdge(v, u, numberOfFlips));}}}return edges;}private static int getNumberOfFlips(int u, int v) {char[] node1 = getNode(u);char[] node2 = getNode(v);int count = 0; // Count the number of different cellsfor (int i = 0; i < node1.length; i++)if (node1[i] != node2[i]) count++;return 3 * count;}public int getNumberOfFlips(int u) {return (int)((WeightedGraph<Integer>.ShortestPathTree)tree).getCost(u);}}}29.9public class Exercise29_09 {public static void main(String[] args) throws Exception {java.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Enter a file name: ");java.io.File file = new java.io.File(input.nextLine());if (!file.exists()) {System.out.println("File does not exist");System.exit(1);}java.util.Scanner inFile = new java.util.Scanner(file);// Read the number of verticesString s = inFile.nextLine();int numberOfVertices = Integer.parseInt(s);System.out.println("The number of vertices is " + numberOfVertices); java.util.List<WeightedEdge> list =new java.util.ArrayList<WeightedEdge>();while (inFile.hasNext()) {s = inFile.nextLine();String[] triplets = s.split("[\\|]");for (String triplet: triplets) {String[] tokens = triplet.split("[,]");int u = Integer.parseInt(tokens[0].trim());int v = Integer.parseInt(tokens[1].trim());int w = Integer.parseInt(tokens[2].trim());list.add(new WeightedEdge(u, v, w));list.add(new WeightedEdge(v, u, w));}}WeightedGraph<Integer> graph = new WeightedGraph<Integer>(list, numberOfVertices);graph.printWeightedEdges();WeightedGraph<Integer>.MST tree = graph.getMinimumSpanningTree();System.out.println("Total weight in MST is " + tree.getTotalWeight()); tree.printTree();}}29.10public class Exercise29_10 {public static void main(String[] args) throws java.io.FileNotFoundException {String[] vertices = {"Seattle", "San Francisco", "Los Angeles", "Denver", "Kansas City", "Chicago", "Boston", "New York","Atlanta", "Miami", "Dallas", "Houston"};int[][] edges = {{0, 1, 807}, {0, 3, 1331}, {0, 5, 2097},{1, 0, 807}, {1, 2, 381}, {1, 3, 1267},{2, 1, 381}, {2, 3, 1015}, {2, 4, 1663}, {2, 10, 1435},{3, 0, 1331}, {3, 1, 1267}, {3, 2, 1015}, {3, 4, 599},{3, 5, 1003},{4, 2, 1663}, {4, 3, 599}, {4, 5, 533}, {4, 7, 1260},{4, 8, 864}, {4, 10, 496},{5, 0, 2097}, {5, 3, 1003}, {5, 4, 533},{5, 6, 983}, {5, 7, 787},{6, 5, 983}, {6, 7, 214},{7, 4, 1260}, {7, 5, 787}, {7, 6, 214}, {7, 8, 888},{8, 4, 864}, {8, 7, 888}, {8, 9, 661},{8, 10, 781}, {8, 11, 810},{9, 8, 661}, {9, 11, 1187},{10, 2, 1435}, {10, 4, 496}, {10, 8, 781}, {10, 11, 239},{11, 8, 810}, {11, 9, 1187}, {11, 10, 239}};java.io.PrintWriter output = newjava.io.PrintWriter("Exercise28_10.txt");int numberOfVertices = vertices.length;output.println(numberOfVertices);for (int startingVertex = 0; startingVertex < numberOfVertices; startingVertex++) {int count = 0;for (int i = 0; i < edges.length; i++) {if (edges[i][0] == startingVertex && edges[i][0] < edges[i][1]) {count++;if (count == 1)output.print(edges[i][0] + ", "+ edges[i][1] + ", "+ edges[i][2]);elseoutput.print(" | " + edges[i][0] + ", " + edges[i][1] + ", " + edges[i][2]);}}if (count > 0) output.println();}System.out.println("Done!");output.close();}}29.11public class Exercise29_11 {public static void main(String[] args) throws Exception {java.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Enter a file name: ");java.io.File file = new java.io.File(input.nextLine());if (!file.exists()) {System.out.println("File does not exist");System.exit(1);}// Read two verticesSystem.out.print("Enter two vertices (integer indexes): ");int v1 = input.nextInt();int v2 = input.nextInt();java.util.Scanner inFile = new java.util.Scanner(file);// Read the number of verticesString s = inFile.nextLine();int numberOfVertices = Integer.parseInt(s);System.out.println("The number of vertices is " + numberOfVertices); java.util.List<WeightedEdge> list = new java.util.ArrayList<>();while (inFile.hasNext()) {s = inFile.nextLine();String[] triplets = s.split("[\\|]");for (String triplet: triplets) {String[] tokens = triplet.split("[,]");int u = Integer.parseInt(tokens[0].trim());int v = Integer.parseInt(tokens[1].trim());int w = Integer.parseInt(tokens[2].trim());list.add(new WeightedEdge(u, v, w));list.add(new WeightedEdge(v, u, w));}}WeightedGraph<Integer> graph = new WeightedGraph<>(list, numberOfVertices);graph.printWeightedEdges();WeightedGraph<Integer>.ShortestPathTree tree =graph.getShortestPath(v1);tree.printPath(v2);}29.12import java.util.List;import javafx.application.Application;import javafx.scene.Scene;import yout.Pane;import javafx.scene.shape.Circle;import javafx.scene.shape.Line;import javafx.scene.text.Text;import javafx.stage.Stage;public class Exercise29_12 extends Application {private City[] vertices = { new City("Seattle", 75, 50),new City("San Francisco", 50, 210),new City("Los Angeles", 75, 275), new City("Denver", 275, 175),new City("Kansas City", 400, 245),new City("Chicago", 450, 100), new City("Boston", 700, 80),new City("New York", 675, 120), new City("Atlanta", 575, 295),new City("Miami", 600, 400), new City("Dallas", 408, 325),new City("Houston", 450, 360) };private int[][] edges = {{0, 1, 807}, {0, 3, 1331}, {0, 5, 2097},{1, 0, 807}, {1, 2, 381}, {1, 3, 1267},{2, 1, 381}, {2, 3, 1015}, {2, 4, 1663}, {2, 10, 1435},{3, 0, 1331}, {3, 1, 1267}, {3, 2, 1015}, {3, 4, 599},{3, 5, 1003},{4, 2, 1663}, {4, 3, 599}, {4, 5, 533}, {4, 7, 1260},{4, 8, 864}, {4, 10, 496},{5, 0, 2097}, {5, 3, 1003}, {5, 4, 533},{5, 6, 983}, {5, 7, 787},{6, 5, 983}, {6, 7, 214},{7, 4, 1260}, {7, 5, 787}, {7, 6, 214}, {7, 8, 888},{8, 4, 864}, {8, 7, 888}, {8, 9, 661},{8, 10, 781}, {8, 11, 810},{9, 8, 661}, {9, 11, 1187},{10, 2, 1435}, {10, 4, 496}, {10, 8, 781}, {10, 11, 239},{11, 8, 810}, {11, 9, 1187}, {11, 10, 239}};private WeightedGraph<City> graph1 = new WeightedGraph<>(vertices, edges); private GraphView view = new GraphView(graph1);@Override // Override the start method in the Application class public void start(Stage primaryStage) {// Create a scene and place it in the stageScene scene = new Scene(view, 450, 350);primaryStage.setTitle("Exercise29_12"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage}class GraphView extends Pane {Graph<? extends Displayable> graph;public GraphView(Graph<? extends Displayable> graph) {this.graph = graph;paint();}protected void paint() {// Draw verticesList<? extends Displayable> vertices = graph.getVertices();for (int i = 0; i < graph.getSize(); i++) {int x = vertices.get(i).getX();int y = vertices.get(i).getY();String name = vertices.get(i).getName();getChildren().addAll(new Circle(x, y, 8),new Text(x - 12, y - 12, name));}// Display edges and weightsfor (int i = 0; i < graph.getSize(); i++) {List<Integer> neighbors = graph.getNeighbors(i);for (int j = 0; j < neighbors.size(); j++) {int v = neighbors.get(j);int x1 = graph.getVertex(i).getX();int y1 = graph.getVertex(i).getY();int x2 = graph.getVertex(v).getX();int y2 = graph.getVertex(v).getY();try {getChildren().addAll(new Line(x1, y1, x2, y2),new Text((x1 + x2) / 2, (y1 + y2) / 2 - 6,((WeightedGraph)graph).getWeight(i, v) + ""));}catch (Exception ex) {ex.printStackTrace();}}}}}class City implements Displayable {private int x, y;private String name;City(String name, int x, int y) { = name;this.x = x;this.y = y;}public int getX() {return x;}public int getY() {return y;}public String getName() {return name;}public boolean equals(Object o) {return ((City)o).name.equals();}}/*** 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);}}29.13import java.util.List;import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import bel;import javafx.scene.control.TextField;import yout.BorderPane;import yout.HBox;import yout.Pane;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.shape.Line;import javafx.scene.text.Text;import javafx.stage.Stage;public class Exercise29_13 extends Application {private City[] vertices = { new City("Seattle", 75, 50), new City("San Francisco", 50, 210),new City("Los Angeles", 75, 275), new City("Denver", 275, 175), new City("Kansas City", 400, 245),new City("Chicago", 450, 100), new City("Boston", 700, 80),new City("New York", 675, 120), new City("Atlanta", 575, 295),new City("Miami", 600, 400), new City("Dallas", 408, 325),new City("Houston", 450, 360) };private int[][] edges = {{0, 1, 807}, {0, 3, 1331}, {0, 5, 2097},{1, 0, 807}, {1, 2, 381}, {1, 3, 1267},{2, 1, 381}, {2, 3, 1015}, {2, 4, 1663}, {2, 10, 1435},{3, 0, 1331}, {3, 1, 1267}, {3, 2, 1015}, {3, 4, 599},{3, 5, 1003},{4, 2, 1663}, {4, 3, 599}, {4, 5, 533}, {4, 7, 1260},{4, 8, 864}, {4, 10, 496},{5, 0, 2097}, {5, 3, 1003}, {5, 4, 533},{5, 6, 983}, {5, 7, 787},{6, 5, 983}, {6, 7, 214},{7, 4, 1260}, {7, 5, 787}, {7, 6, 214}, {7, 8, 888},{8, 4, 864}, {8, 7, 888}, {8, 9, 661},{8, 10, 781}, {8, 11, 810},{9, 8, 661}, {9, 11, 1187},{10, 2, 1435}, {10, 4, 496}, {10, 8, 781}, {10, 11, 239},{11, 8, 810}, {11, 9, 1187}, {11, 10, 239}};private WeightedGraph<City> graph1 = new WeightedGraph<>(vertices, edges); private GraphView view = new GraphView(graph1);private Label lblStatus = new Label();private TextField tfStartCity = new TextField();private TextField tfEndCity = new TextField();private Button btSP = new Button("Display Shortest Path");@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {HBox hBox = new HBox();hBox.getChildren().addAll(new Label("Starting City:"),tfStartCity, new Label("Ending City:"), tfEndCity, btSP);hBox.setAlignment(Pos.CENTER);BorderPane pane = new BorderPane();pane.setCenter(view);pane.setBottom(hBox);pane.setTop(lblStatus);BorderPane.setAlignment(lblStatus, Pos.CENTER);// Create a scene and place it in the stageScene scene = new Scene(pane, 450, 350);primaryStage.setTitle("Exercise29_13"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stagebtSP.setOnAction( e -> {String name1 = tfStartCity.getText();int index1 = graph1.getIndex(new City(name1, 0, 0));if (index1 < 0) {lblStatus.setText(name1 + " is not in the map");return;}String name2 = tfEndCity.getText();int index2 = graph1.getIndex(new City(name2, 0, 0));if (index2 < 0)lblStatus.setText(name2 + " is not in the map");else {List<City> path = graph1.getShortestPath(index1).getPath(index2); view.setPath(path);}});}class GraphView extends Pane {private Graph<? extends Displayable> graph;private List<? extends Displayable> path;public GraphView(Graph<? extends Displayable> graph) {this.graph = graph;paint();}public void setPath(List<? extends Displayable> path) {this.path = path;paint();}protected void paint() {// Draw verticesList<? extends Displayable> vertices = graph.getVertices();for (int i = 0; i < graph.getSize(); i++) {int x = vertices.get(i).getX();int y = vertices.get(i).getY();String name = vertices.get(i).getName();getChildren().addAll(new Circle(x, y, 8),new Text(x - 12, y - 12, name));}// Display edges and weightsfor (int i = 0; i < graph.getSize(); i++) {List<Integer> neighbors = graph.getNeighbors(i);for (int j = 0; j < neighbors.size(); j++) {int v = neighbors.get(j);int x1 = graph.getVertex(i).getX();int y1 = graph.getVertex(i).getY();int x2 = graph.getVertex(v).getX();int y2 = graph.getVertex(v).getY();try {getChildren().addAll(new Line(x1, y1, x2, y2), new Text((x1 + x2) / 2, (y1 + y2) / 2 - 6, ((WeightedGraph)graph).getWeight(i, v) + ""));}catch (Exception ex) {ex.printStackTrace();}}}// Display the pathif (path == null) return;for (int i = 1; i < path.size(); i++) {int x1 = path.get(i).getX();int y1 = path.get(i).getY();int x2 = path.get(i - 1).getX();int y2 = path.get(i - 1).getY();Line line = new Line(x1, y1, x2, y2);line.setStroke(Color.RED);line.setStrokeWidth(3);this.getChildren().add(line);}}}class City implements Displayable {private int x, y;private String name;City(String name, int x, int y) { = name;this.x = x;this.y = y;}public int getX() {return x;}public int getY() {return y;}public String getName() {return name;}public boolean equals(Object o) {return ((City)o).name.equals();}}/*** 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);}}29.14import java.util.List;import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import bel;import javafx.scene.control.TextField;import yout.BorderPane;import yout.Pane;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.shape.Line;import javafx.scene.text.Text;import javafx.stage.Stage;public class Exercise29_14 extends Application {private City[] vertices = { new City("Seattle", 75, 50),new City("San Francisco", 50, 210),new City("Los Angeles", 75, 275), new City("Denver", 275, 175), new City("Kansas City", 400, 245),new City("Chicago", 450, 100), new City("Boston", 700, 80),new City("New York", 675, 120), new City("Atlanta", 575, 295), new City("Miami", 600, 400), new City("Dallas", 408, 325),new City("Houston", 450, 360) };private int[][] edges = {{0, 1, 807}, {0, 3, 1331}, {0, 5, 2097},{1, 0, 807}, {1, 2, 381}, {1, 3, 1267},{2, 1, 381}, {2, 3, 1015}, {2, 4, 1663}, {2, 10, 1435},{3, 0, 1331}, {3, 1, 1267}, {3, 2, 1015}, {3, 4, 599},{3, 5, 1003},{4, 2, 1663}, {4, 3, 599}, {4, 5, 533}, {4, 7, 1260},{4, 8, 864}, {4, 10, 496},{5, 0, 2097}, {5, 3, 1003}, {5, 4, 533},{5, 6, 983}, {5, 7, 787},{6, 5, 983}, {6, 7, 214},{7, 4, 1260}, {7, 5, 787}, {7, 6, 214}, {7, 8, 888},{8, 4, 864}, {8, 7, 888}, {8, 9, 661},{8, 10, 781}, {8, 11, 810},{9, 8, 661}, {9, 11, 1187},{10, 2, 1435}, {10, 4, 496}, {10, 8, 781}, {10, 11, 239},{11, 8, 810}, {11, 9, 1187}, {11, 10, 239}};private WeightedGraph<City> graph1 = new WeightedGraph<>(vertices, edges); private GraphView view = new GraphView(graph1,graph1.getMinimumSpanningTree());private Label lblStatus = new Label();private TextField tfStartCity = new TextField();private TextField tfEndCity = new TextField();private Button btSP = new Button("Display Shortest Path");@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {BorderPane pane = new BorderPane();pane.setCenter(view);BorderPane.setAlignment(lblStatus, Pos.CENTER);// Create a scene and place it in the stageScene scene = new Scene(pane, 450, 350);primaryStage.setTitle("Exercise29_14"); // Set the stage titleprimaryStage.setScene(scene); // Place the scene in the stageprimaryStage.show(); // Display the stage}class GraphView extends Pane {private Graph<? extends Displayable> graph;private AbstractGraph<? extends Displayable>.Tree tree;public GraphView(Graph<? extends Displayable> graph,AbstractGraph<? extends Displayable>.Tree tree) {this.graph = graph;this.tree = tree;paint();}public void setTree(AbstractGraph<? extends Displayable>.Tree tree) { this.tree = tree;paint();}protected void paint() {// Draw verticesList<? extends Displayable> vertices = graph.getVertices();for (int i = 0; i < graph.getSize(); i++) {int x = vertices.get(i).getX();int y = vertices.get(i).getY();String name = vertices.get(i).getName();getChildren().addAll(new Circle(x, y, 8),new Text(x - 12, y - 12, name));}// Display edges and weightsfor (int i = 0; i < graph.getSize(); i++) {List<Integer> neighbors = graph.getNeighbors(i);for (int j = 0; j < neighbors.size(); j++) {int v = neighbors.get(j);int x1 = graph.getVertex(i).getX();int y1 = graph.getVertex(i).getY();int x2 = graph.getVertex(v).getX();int y2 = graph.getVertex(v).getY();try {getChildren().addAll(new Line(x1, y1, x2, y2),new Text((x1 + x2) / 2, (y1 + y2) / 2 - 6,((WeightedGraph)graph).getWeight(i, v) + ""));}catch (Exception ex) {ex.printStackTrace();}}}// Highlight the edges in the spanning treeif (tree == null) return;for (int i = 0; i < graph.getSize(); i++) {if (tree.getParent(i) != -1) {int v = tree.getParent(i);int x1 = graph.getVertex(i).getX();int y1 = graph.getVertex(i).getY();int x2 = graph.getVertex(v).getX();int y2 = graph.getVertex(v).getY();drawArrowLine(x1, y1, x2, y2, this);}}}}public static void drawArrowLine(double x1, double y1, double x2, double y2, Pane pane) {Line line1 = new Line(x1, y1, x2, y2);line1.setStroke(Color.RED);pane.getChildren().add(line1);// find slope of this linedouble slope = ((((double) y1) - (double) y2))/ (((double) x1) - (((double) x2)));double arctan = Math.atan(slope);// This will flip the arrow 45 off of a// perpendicular line at pt x2double set45 = 1.57 / 2;// arrows should always point towards i, not i+1if (x1 < x2) {// add 90 degrees to arrow linesset45 = -1.57 * 1.5;}// set length of arrowsint arrlen = 15;// draw arrows on lineLine line2 = new Line(x2, y2, (x2 + (Math.cos(arctan + set45) * arrlen)), ((y2)) + (Math.sin(arctan + set45) * arrlen));line2.setStroke(Color.RED);pane.getChildren().add(line2);Line line3 = new Line(x2, y2, (x2 + (Math.cos(arctan - set45) * arrlen)), ((y2)) + (Math.sin(arctan - set45) * arrlen));line3.setStroke(Color.RED);pane.getChildren().add(line3);}class City implements Displayable {private int x, y;private String name;City(String name, int x, int y) { = name;this.x = x;this.y = y;}public int getX() {return x;}public int getY() {return y;}public String getName() {return name;}public boolean equals(Object o) {return ((City)o).name.equals();}}/*** 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);}}29.15import java.util.List;import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import bel;import javafx.scene.control.TextField;import yout.BorderPane;import yout.GridPane;import yout.HBox;import yout.Pane;import yout.VBox;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.shape.Line;import javafx.scene.text.Text;import javafx.stage.Stage;public class Exercise29_15 extends Application {private TextField tfVertexName = new TextField();private TextField tfX = new TextField();private TextField tfY = new TextField();private Button btAddVertex = new Button("Add Vertex");private TextField tfu = new TextField();private TextField tfv = new TextField();private TextField tfWeight = new TextField();private Button btAddEdge = new Button("Add Edge");private TextField tfStartVertex = new TextField();private TextField tfEndVertex = new TextField();private Button btFindShortestPath = new Button("Shortest Path");private Button btStartOver = new Button("Start Over (Clear Graphs)"); private Label lblStatus = new Label();private WeightedGraph<Vertex> graph = new WeightedGraph<>(); private GraphView view = new GraphView(graph);@Override // Override the start method in the Application class public void start(Stage primaryStage) {GridPane gridPane1 = new GridPane();gridPane1.add(new Label("Add a new vertex"), 0, 0);gridPane1.add(new Label("Vertex name:"), 0, 1);gridPane1.add(new Label("x-coordinate:"), 0, 2);gridPane1.add(new Label("y-coordinate:"), 0, 3);gridPane1.add(tfVertexName, 1, 1);gridPane1.add(tfX, 1, 2);gridPane1.add(tfY, 1, 3);gridPane1.add(btAddVertex, 1, 4);GridPane gridPane2 = new GridPane();gridPane2.add(new Label("Add a new edge"), 0, 0);gridPane2.add(new Label("Vertex u (index):"), 0, 1);gridPane2.add(new Label("Vertex v (index):"), 0, 2);gridPane2.add(new Label("Weight:"), 0, 3);gridPane2.add(tfu, 1, 1);gridPane2.add(tfv, 1, 2);gridPane2.add(tfWeight, 1, 3);gridPane2.add(btAddEdge, 1, 4);GridPane gridPane3 = new GridPane();gridPane3.add(new Label("Find a shortest path"), 0, 0);gridPane3.add(new Label("Starting vertex:"), 0, 1);gridPane3.add(new Label("Ending vertex:"), 0, 2);gridPane3.add(tfStartVertex, 1, 1);gridPane3.add(tfEndVertex, 1, 2);gridPane3.add(btFindShortestPath, 1, 3);HBox hBox = new HBox(5);hBox.setAlignment(Pos.CENTER);hBox.getChildren().addAll(gridPane1, gridPane2, gridPane3);VBox vBox = new VBox(5);vBox.setAlignment(Pos.CENTER);vBox.getChildren().addAll(hBox, btStartOver);BorderPane pane = new BorderPane();pane.setCenter(view);pane.setBottom(vBox);BorderPane.setAlignment(lblStatus, Pos.CENTER);。

合集下载

java语言程序设计课后答案

java语言程序设计课后答案

java语言程序设计课后答案作业参考答案习题一4、如何建立和运行Java程序,首先启动文本编辑器,如记事本、UltraEdit等,编辑程序代码,并以.Java作为文件扩展名保存程序源代码;然后进入dos环境利用javac编译源程序,生成扩展名为.class的字节码文件;再利用命令java运行字节码文件,得到程序的运行结果。

在集成开发环境Jbuilder、Eclipse下,可以完成程序的编辑、编译、调试及运行等所有任务。

5、public class LikeJava{public static void main(String [] args){System.out.println(“I Like Java Very much!”);}}习题二5、(1) 45 (2) false (3) 14 (4) 14 (5),6 (6) true(7) 129、public class Volume{public static void main(String [] args) {double r=0,v=0;r=double.parseDouble(args[0]);v=4*3.14159/3*r*r*r;System.out.println(“球体积为:”+v);}}习题三8、public class Factorials {public static void main(String args[]) {int i, j;long s=0, k;i=1;do //外循环开始{k = 1;j=1;do{//内循环开始k = k * j; //内循环体j++;}while(j<=i);//内循环结束System.out.println(i + "!=" + k);s = s + k;i++;}while(i<=20); //外循环结束System.out.println("Total sum=" + s); }}10、public class Num{public static void main(String[]args) {int i,j,k,n;for (n=100;n<1000;n++){i=n/100;j=(n-i*100)/10;k=n%10;if (i*i*i+j*j*j+k*k*k==n)System.out.print(n+" ");}}}习题四5、import java.util.Scanner;class Factor{long fac(int m){if(m==0||m==1)return 1;else return m*fac(m-1);}public static void main(String [] args){int i,n;long sum=0;String s="";Scanner input=new Scanner(System.in);System.out.print("Please input n: ");n=input.nextInt();Factor f=new Factor();for(i=1;i<=n;i++){ System.out.println(f.fac(i));sum=sum+f.fac(i);s=s+i+"!+";}System.out.println(s.substring(0,s.length()-1)+"="+sum); }}习题五2、import java.io.*;public class YangHuiOk{public static void main (String args[]) throws IOException {int max,a[][],i,j;char x;System.out.print("请输入杨辉三角要显示的行数: ");x=(char)System.in.read();max = Integer.parseInt(String.valueOf(x));a=new int[max][];for (i=0;i<max;i++){a[i]=new int[i+1];}a[0][0]=1;for (i=1;i<max;i++){a[i][0]=1;a[i][a[i].length-1]=1;for (j=1;j<a[i].length-1;j++){a[i][j]=a[i-1][j-1]+a[i-1][j];}}for(i=0;i<max;i++){//for(j=0;j<=max-i;j++) System.out.print(" ");for(j=0;j<=a[i].length-1;j++) System.out.print(a[i][j]+" "); System.out.println();}}}5、import java.util.Scanner;public class MatrixTurn {public static void main (String[] args) {int m,n;Scanner input=new Scanner(System.in);System.out.print("请输入矩阵的行数: ");m=input.nextInt();System.out.print("请输入矩阵的列数: ");n=input.nextInt();Matrix t=new Matrix(m,n);for(int i=1;i<=m;i++)//为矩阵各元素赋值for (int j=1;j<=n;j++)t.setElement(Math.random(),i,j);System.out.println("转置前的矩阵如下: ");for(int i=1;i<=m;i++){for (int j=1;j<=n;j++)//System.out.print(t.matrix[i][j]+" ");System.out.print(t.getElement(i,j)+" ");//访问矩阵元素方法1 System.out.println();}Matrix z;//声明转置矩阵z=t.turn(t);System.out.println("转置后的矩阵如下: ");for(int i=0;i<n;i++){for (int j=0;j<m;j++)System.out.print(z.matrix[i][j]+" ");//访问矩阵元素方法2,前提是matrix前无privateSystem.out.println();}}}习题六9、public class Vehicle,String color, kind;int speed;Vehicle(){color=”Red”;kind=”卡车”;speed=0;}public void setColor(String color1) { color=color1;}public void setSpeed(String speed1) { speed=speed1;}public void setKind(String kind1) { kind=kind1;}public String getColor( ) {return color;}public String getKind( ) {return kind;}public int getSpeed( ) {return speed;}public static void main(String [] args){Vehicle che=new Vehicle ();Che.setColor(“Blue”);Che.setSpeed(150);Che.setKind(“跑车”);System.out.p rintln(“有一辆”+che.getColor()+”的”+che.getKind()+”行驶在高速公路上”);System.out.println(“时速”+che.getSpeed()+”km/h”); }}习题七 7、public class Vehicle ,String color, kind;int speed;Vehicle(){color=” ”;kind=” ”;speed=0;}public void setColor(String color1){color=color1;}public void setSpeed(String speed1) {speed=speed1;}public void setKind(String kind1) {kind=kind1;}public String getColor( ) {return color;}public String getKind( ) {return kind;}public int getSpeed( ) {return speed;}}public class Car extends Vehicle {int passenger;public Car(){super();passenger=0;}public void setPassenger(int passenger){this. passenger = passenger; }public int getPassenger( ) {return passenger;}public static void main(String [] args){Car benz=new Car();benz.setColor(“Yellow”);benz.setKind(“roadster”);benz.setSpeed(120);benz.setPassenger(4);System.out.println(“benz: “);System.out.println(“Color “+benz.getColor());System.out.print(“Speed (km/h)“);System.out.println(benz.getSpeed()); System.out.println(“Kind: “+benz.getKind()); System.out.print(“Passenger: “);System.out.println(benz.getPassenger());}}习题九4、import java.io.*;public class UseException{public static void main(String [] args){System.out.println("请输入一个整数字符串");try{BufferedReader in=new BufferedReader(new InputStreamReader(System.in));int a=Integer.parseInt(in.readLine());System.out.println("您输入的整数是:"+a);}catch(IOException e){System.out.println("IO错误");}catch(NumberFormatException e1){System.out.println("您输入的不是一个整数字符串");}}}习题十 7、import java.io.*;public class SaveName {public static void main(String [] args){try{BufferedReader br=new BufferedReader(newInputStreamReader(System.in));BufferedWriter bw=new BufferedWriter(new FileWriter("name.txt"));String s;while(true){System.out.println("请输入姓名:");s=br.readLine();if(s.length()==0)break;bw.write(s);bw.newLine();}br.close();bw.close();}catch(FileNotFoundException e){System.out.println(e.toString());}catch(IOException e1){System.out.println(e1.toString());}}}8、import java.io.*;public class SaveGrade{public static void main(String [] args){try{BufferedReader br=new BufferedReader(newInputStreamReader(System.in));BufferedWriter bw=new BufferedWriter(new FileWriter("grade.txt"));String s,ss;while(true){System.out.println("请输入姓名:");s=br.readLine();if(s.length()==0)break;bw.write(s);bw.newLine();System.out.println("请输入学号:");s=br.readLine();bw.write(s);bw.newLine();System.out.println("请输入成绩:");s=br.readLine();bw.write(s);bw.newLine();}br.close();bw.close();int max=0,min=100,total=0,num=0;BufferedReader bf=new BufferedReader(new FileReader("grade.txt")); while(true){ss=bf.readLine();if(ss==null)break;ss=bf.readLine();ss=bf.readLine();int grade=Integer.parseInt(ss);total+=grade;num+=1;if(grade>max)max=grade;if(grade<min)min=grade;}System.out.println("学生成绩中最高为:"+max+",最低为:"+min+",平均分为:"+total*1.0/num);bf.close();}catch(FileNotFoundException e){System.out.println(e.toString());}catch(IOException e1){System.out.println(e1.toString());}}}习题十一6、import java.awt.*;import java.awt.event.*;public class ChangeColor extends Frame { private Button red=new Button("红");private Button green=new Button("绿"); private Button blue=new Button("蓝"); private TextField text=new TextField(); public ChangeColor(){super("改变颜色");this.setLayout(null);text.setBackground(Color.WHITE);red.setBounds(25,50,50,20);this.add(red);green.setBounds(125,50,50,20);this.add(green);blue.setBounds(225,50,50,20);this.add(blue);text.setBounds(25,100,250,30);this.add(text);red.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) {text.setBackground(Color.RED);}});green.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) {text.setBackground(Color.GREEN);}});blue.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) {text.setBackground(Color.BLUE);}});addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});setSize(300,200);setVisible(true);}public static void main (String[] args){ChangeColor color=new ChangeColor(); }}习题十二5、import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Goods extends JFrame {private JComboBox list;private JTextArea info;private String names[]={"请选择你要查询的商品","A商品","B商品","C商品","D商品","E商品","F商品"};private String goods[][]={ {"","",""},{"A商品","北京",",300"},{"B商品","上海",",400"},{"C商品","广州",",500"},{"D商品","长沙",",600"},{"E商品","武汉",",700"},{"F商品","天津",",800"}};public Goods(){super("商品信息");Container pane=this.getContentPane();pane.setLayout(new BorderLayout());list=new JComboBox(names);info=new JTextArea(5,20);pane.add(list,BorderLayout.NORTH);pane.add(info,BorderLayout.CENTER);list.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent e) {int index=list.getSelectedIndex();info.setText("商品名:"+goods[index][0]+"\n"); info.append("产地:"+goods[index][1]+"\n"); info.append("价格:"+goods[index][2]+"\n"); }});this.setSize(250,300);this.setVisible(true);}public static void main (String[] args) {Goods ccc=new Goods();ccc.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) {System.exit(0);}});}}。

《JAVA程序设计》(含答案)

《JAVA程序设计》(含答案)

《JA V A程序设计》练习题一、单选择题1、编译Java Application 源程序文件将产生相应的字节码文件,这些字节码文件的扩展名为( B )。

A. javaB. .classC. htmlD. .exe2、设x = 1 , y = 2 , z = 3,则表达式y+=z--/++x 的值是( A)。

A. 3B. 3. 5C. 4D. 53、不允许作为类及类成员的访问控制符的是( C )。

A. publicB. privateC. staticD. protected4、为AB类的一个无形式参数无返回值的方法method书写方法头,使得使用类名AB作为前缀就可以调用它,该方法头的形式为( A)。

A. static void method( )B. public void method( )C. final void method( )D. abstract void method( )5、关于选择结构下列哪个说法正确?( B )A.if语句和else语句必须成对出现B.if语句可以没有else语句对应C.switch结构中每个case语句中必须用break语句D.switch结构中必须有default语句6、while循环和do…while循环的区别是:( D)A.没有区别,这两个结构任何情况下效果一样B.while循环比do…while循环执行效率高C.while循环是先循环后判断,所以循环体至少被执行一次D.do…while循环是先循环后判断,所以循环体至少被执行一次7、关于for循环和while循环的说法哪个正确?( B)A.while循环先判断后执行,for循环先执行后判断。

B.while循环判断条件一般是程序结果,for循环的判断条件一般是非程序结果C.两种循环任何时候都不可以替换D.两种循环结构中都必须有循环体,循环体不能为空8、下列修饰符中与访问控制无关的是( D)A.private B.publicC.protected D.final9、void的含义:( A)A.方法没有返回值B.方法体为空C.没有意义 D.定义方法时必须使用10、return语句:( C )A.只能让方法返回数值B.方法都必须含有C.方法中可以有多句return D.不能用来返回对象11、关于对象成员占用内存的说法哪个正确?( B)A.同一个类的对象共用同一段内存B、同一个类的对象使用不同的内存段,但静态成员共享相同的内存空间C.对象的方法不占用内存D.以上都不对12、下列说法哪个正确?( C)A.不需要定义类,就能创建对象B.对象中必须有属性和方法C.属性可以是简单变量,也可以是一个对象D、属性必须是简单变量13、下列说法哪个正确?( A )A、一个程序可以包含多个源文件B、一个源文件中只能有一个类C、一个源文件中可以有多个公共类D、一个源文件只能供一个程序使用14、关于方法main()的说法哪个正确?( C )A.方法main()只能放在公共类中B main()的头定义可以根据情况任意更改C.一个类中可以没有main()方法D.所有对象的创建都必须放在main()方法中15、构造函数何时被调用?( A )A、创建对象时B、类定义时C、使用对象的方法时D、使用对象的属性时16、抽象方法:( C )A、可以有方法体B、可以出现在非抽象类中C、是没有方法体的方法D、抽象类中的方法都是抽象方法17、关于继承的说法正确的是:( B )A、子类将继承父类所有的属性和方法。

Java程序设计基础习题答案

Java程序设计基础习题答案

Java程序设计基础课后习题参考答案第2章1. 关于Java Application 的入口方法main()的检验:main()方法的参数名是否可以改变main()方法的参数个数是否可以改变该方法名是否可以改变参考答案:(1)main()方法的参数名可以改变。

(2)main()方法的参数个数不可以改变。

(3)该方法名不可以改变。

2. 当一个程序没有main()方法时,能编译吗如果能编译,能运行吗参考答案:当一个程序没有main()方法是,是可以编译通过的,但是不能给运行,因为找不到一个主函数入口。

3. 下列语句能否编译通过byte i = 127;byte j = 128;long l1 = 999999;long l2 = 99;参考答案:byte i 和 long l1可以编译通过。

而 byte j 和long l2 超出自身数据类型范围,所以编译失败。

4. 下列语句能否编译通过float f1 = ;float f2 = 3.5f;参考答案:java中浮点型的数据在不声明的情况下都是double型的,如果要表示一个数据是float型的,必须在数据后面加上“F”或“f”;因此,float f1 无法编译通过。

5. 验证int 和char,int和double等类型是否可以相互转换。

参考答案:(1)char类型可以转换为int 类型的,但是int类型无法转换为char 类型的;(2)int 可以转换为 double类型的,但是double类型无法转换为int 类型的。

6. 计算下列表达式,注意观察运算符优先级规则。

若有表达式是非法表达式,则指出不合法之处且进行解释。

(1) 4+5 == 6*2 (2) (4=5)/6(3) 9%2*7/3>17 (4) (4+5)<=6/3(5) 4+5%3!=7-2 (6) 4+5/6>=10%2参考答案:表达式(2)为不合法表达式,只能将值赋值给一个变量,因此其中(4=5)将5赋值给4是不合法的。

《Java基础程序设计》_课后习题

《Java基础程序设计》_课后习题

第一章思考题】1、简述path 环境变量的作用。

2、请说说你对JVM 的理解。

答案】1、path 环境变量是系统环境变量中的一种,它用于保存一系列可执行文件的路径,每个路径之间以分号分隔。

当在命令行窗口运行一个可执行文件时,操作系统首先会在当前目录下查找是否存在该文件,如果不存在会继续在path 环境变量中定义的路径下去寻找这个文件,如果仍未找到,系统会报错。

2、JVM 是Java Virtual Machine 的缩写,全称是Java 虚拟机。

Java 语言的一个非常重要的特性就是跨平台性,而Java 虚拟机是实现这一特性的关键。

不同的操作系统需要使用不同版本的虚拟机,这种方式使得Java语言能够“一次编写,到处运行”。

Java语言编译程序只需生成在Java 虚拟机上运行的目标代码(字节码),就可以在多种平台上不加修改地运行。

Java虚拟机在执行字节码时,把字节码解释成具体平台上的机器指令执行。

第二章【思考题】1、请简述& 与&& 的区别。

2、简述break、continue 和return 语句的区别。

【答案】1、&和&&都可以用作逻辑与的运算符,表示逻辑与(and),当运算符两边的表达式的结果都为true时,整个运算结果才为true,否则,只要有一方为false,则结果为false。

当运算符“ &”和“ && ”的右边为表达式时,使用“ &”进行运算,不论左边为true 或者false,右边的表达式都会进行运算。

如果使用" && ”进行运算,当左边为false时,右边的表达式则不会进行运算,因此“ && ”被称作短路与。

2、break 语句:在switch 条件语句和循环语句中都可以使用break 语句。

当它出现在switch 条件语句中时,作用是终止某个case并跳出switch结构。

(完整版)Java语言程序设计(基础篇)原书第十版梁勇著第一章答案

(完整版)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语言程序设计方案基础篇答案

java语言程序设计方案基础篇答案

在一个正n边形中,所以边的长度都相同,且所有角的度数都相同(即这个多边形是等边等角的)。

设计一个名为RegularPolygon的类,该类包括:一个名为int型的私有数据域定义多边形的边数,默认值3。

一个名为side的double型私有数据域存储边的长度,默认值1。

一个名为x的double型私有数据域,它定义多边形中点的x坐标,默认值0。

一个名为y 的double型私有数据域,它定义多边形中点的y坐标,默认值0。

一个创建带默认值的正多边形的无参构造方法。

一个能创建带指定边数和边长度、中心在(0,0)的正多边形的构造方法。

一个能创建带指定边数和边长度、中心在(x,y)的正多边形的构造方法。

所有数据域的访问器和修改器。

一个返回多边形周长的方法getPerimeter()。

一个返回多边形面积的方法getArea().计算多边形面积的公式是:面积=(n*s*s)/(4*tan(p/n)) 画出该类的UML图。

实现这个类。

编写一个测试程序,分别使用无参构造方法、RegularPolygon(6,4)和RegularPolygon(10,4,5.6,7.8)创建三个RegularPolygon对象。

显示每个对象的周长和面积。

代码:class Regularpolygon{private int n=3。

//边长private double side=1。

//边长private double x=0。

private double y=0。

//x,y为多边形中点的x,y坐标Regularpolygon(){}Regularpolygon(int newN,int newS){n=newN。

side=newS。

x=0。

y=0。

}Regularpolygon(int newN,int newS,double newX,double newY){n=newN。

side=newS。

x=newX。

y=newY。

}public void setN(int newN){n=newN。

java程序设计基础(含参考答案)

“Java程序设计基础”课程习题一、填空1.Java程序分两类___Applet___和application,Java Application 类型的程序,程序从___main方法___开始执行。

2.定义一个Java类时,通过关键字__extends____指明该类的父类。

一个类可以有___1___个父类。

3.用public修饰的类称为_公有类或公用类__。

用public修饰的类成员称为公有成员。

被说明为public的内容可以被__所有其他类___ 使用。

如果public类文件与使用它的类文件不在同一目录中,需要通过__import____语句引入。

4.用___private___ 修饰的类成员称为私有成员。

私有成员只能在__本类__ 中使用。

5.如果子类定义的成员变量与父类的成员变量同名,称为___方法覆盖___ ,要表明使用子类的成员变量,可以在成员变量前加上关键字__super___ 。

6.____Object__ 类是Java类库中所有类的父类。

7.Java字符使用__16位的字符集,该字符集成为__Unicode____ 。

8.当子类中定义的方法与父类方法同名时,称子类方法___覆盖___ 父类方法,子类默认使用自己的方法。

使用父类的同名方法,必须用关键字__super__ 说明。

9.Java源程序文件名的后缀是___.java___,Java字节码文件名的后缀是_.class_____。

10.Java类名的第一个字母通常要求___大写___。

11.Java程序由____类__组成,每个程序有一个主类,Java程序文件名应与____主__类的名称相同。

12.Java__Application_类型的程序需要main()方法,程序从__main____开始执行。

13.布尔型数据类型的关键字是_boolean__ ,占用位数是___1位___ ,有__true__ 和_false_两种值。

答案JAVA程序设计基础(复习提纲及练习题

复习....参考考试题型:1.单项选择题(本大题共15小题,每小题1分,共15分)2. 判断题(10小题,每小题1分,共10分)3.填空题(本大题共10空,每个空2分,共20分)4.阅读程序,写出程序运行后的输出结果(本大题共3小题,每小题6分,共18分)5. 编程题(本大题共3小题,共37分),其中第1题:9分(位操作),第2题14(分排序或字符串处理),第3题14分(类与对象)。

涉及数组、排序、字符串处理、类和对象(实例)、位操作(手写推算步骤及最终结果,要求看样题)等。

考试涉及的相关知识点:1.java程序类型:(1)java application(需主类)、java程序、源程序、类、接口、字节码文件、包、JDK JVM javac.exe java.exe跨平台java开发步骤一二维数组等(2)java applet:java小程序(可以没有主类,是图形界面),主要用于网页(3)java script:网页或网站的“脚本”程序2.标识符和关键字:class、interface final abstract static void byte short int long float double boolean String return 异常常用的关键字(try catch finally throw throws)3.表达式:=比较运算符:> >= < <= != ==逻辑运算符:&& || !位运算符:& |~ ^ >> >>> <<instanceof ++ -- 前后关系?:算合语句s+=5 s-=5 s*=5 s/=5 int a=b=10;4.程序控制结构:顺序、选择、循环(1)单路选择结构if(){ }(2)多路选择结构if( ) {.. else ..}(3)else if 结构(4)switch (break);while(){ … }do{ …. } while( ); break continuefor( ; ; ){ … }5.面向对象的程序设计:类:class 成员变量方法成员修饰符(访问、特征)static变量成员或方法实例变量成员或方法UML图对象:Object 创造对象new方法:void 方法、非void 方法、static 方法(类方法)、非static 方法(实例方法)方法参数传递:实参形参传值传引用(数组对象接口)多态:重载重写this 、super构造方法(在类的继承中可能用到的关键字super)包:关键字import 、package继承(组合:主类main() 与继承):继承创新改造子类不能降低父类的访问级别Super、this 、上转型对象Abstract、final接口:interface(1)实现:implements 也是一种继承(包括一般类与抽象类,多实现)(2)继承:extends (与类相比的“多继承”)(3)静态块(静态初始化器) static { …}、构造块{…}、构造方法以及在类的继承和实例生成中的相互关系和执行顺序。

Java程序设计基础习题答案

Java程序设计基础习题答案第1章1选择题(1)BCD (2)D (3)CD (4)CD第2章1、错误:-0x3221 fa00 8.33E e-10整数:1856 4l 021 0xa6 0xa2e3 35 -78999 0L浮点数:0x3.45 -3.81 1.34e-8 -.67e3 25. 053.249 -1E3八进制数:053.249 021十六进制数:0xa6 0x3.45 0xa2e32、正确的标识符:_book, book3, _9days, I, copy_file, _56, up_down, if_count, agentEventListener 错误的标识符:int, println, static, a$, 5files, -number, date:x, +digit, $abcd,3、(1)int i改为static int i。

(2)j=i 改为j=(short)i。

(3)i为数组,应该改为int i[] = new int[10]。

同时后面也要做相应修改。

(4)将k=i&j改为k= (Boolean)i&j。

4、x=10, y=6, z=false(1)false(2)x=16(3)true(4)x=60(5)6(6)6(7)true(8)false5、x=5, y=7, z=0(1)35(2)-1(3)6(4)13(5)36、(1)x>=y?10:3 y%=(2)x<10 i>6 j==5 && || y=(3)b+c +d a-=(4)a<b ||x &y第3章1、选择题(1)C (2)B (3)无答案,全部正确,不过A for(;;);t选项是个死循环,但不存在语法错误(4)C (5)A (6)B2、(1)全部为0(2)m=34 0到99所有被3整除的数N=15 0到99所有被7整除的数3、(1)char ch =0;try{System.out.println("please input:");ch = (char)System.in.read();} catch(Exception e){e.printStackTrace();}switch(ch) {case 'L':System.out.println("Left");break;case 'R':System.out.println("Right");break;default:System.out.println("Not Known");}(2)int i =1, n=0;for(n=11;n<0;n--)i =i*n;(3)int i =1, n=0;i=1;n=0;for(i=1;i<11;i++)System.out.println("number: " + i +" sum: " + (n=n+i)); (4)int n=4,i=0, j=0;int a[][] = new int[n][n];for(i=0;i<n;i++)for(j=0;j<n;j++)if (i==j)a[i][j] = 1;elsea[i][j] = 0;第4章1选择题(1)D (2)B (3)C (4)B (5)AC (6)C 2判断题m in main = aa in main = 4return from testV ar2 : a in testV ar3 is 547554m+a= 603、编程题(1)public class abc {public abc() {} int factorial(int x) {int rst =1;for(int i=1;i<=x;i++)rst *= i;return rst;}void printf(int x, int rst) {System.out.println(x+"的阶乘是: " +rst);}public static void main(String args[]) {int i =0;abc myabc = new abc();myabc.printf(6,myabc.factorial(6));myabc.printf(9,myabc.factorial(9));}}(2)int factorial(int x) {if (x <1) return 0;else {if(x==1) return 1;elsereturn x*factorial(x-1);}}第5章1、选择题(1)B (2)D (3) A (4)A (5)C (6)A (7)A (8)C (9)D (10)D2、运行结果:X=130, y=45X+y=175x-y=95x*y=5850x/y=2.888888888888889更改后的两个类:class Excer{public static void main(String[] args) {new Excer().math();}int x=130, y=45;Math myMath = new Math();System.out.println("x="+x+" , y="+y);System.out.println("x+y=" + myMath.plus(x,y));System.out.println("x-y=" + myMath.minus(x,y));System.out.println("x*y=" + myMath.multi(x,y));System.out.println("x/y=" + myMath.div(x,y));}}class Math {int plus(int a, int b) {return a+b;}int minus(int a, int b) {return a-b;}int multi(int a, int b) {return a*b;}float div(int a, int b) {return((float)a/b);}}3、编程题(1)class PlayCard {private Poker poker;public PlayCard() {poker = new Poker();}public String play() {int i=0,j=0;java.util.Random ab = new java.util.Random();i = ab.nextInt(13);j = ab.nextInt(4);return (poker.nums[i] + " of " + poker.colors[j]); }public String play(int x, int y) {return (poker.nums[x] + " of " + poker.colors[y]); }}(2)class Poker {public String nums[];public String colors[];nums = new String[13];colors = new String[4];nums[0] = "Ace";nums[1] = "Two";nums[2] = "Three";nums[3] = "Four";nums[4] = "Five";nums[5] = "Six";nums[6] = "Seven";nums[7] = "Eight";nums[8] = "Nine";nums[9] = "Ten";nums[10] = "Jack";nums[11] = "Queen";nums[12] = "King";colors[0] = "Diamonds";colors[1] = "Clubs";colors[2] = "Hearts";colors[3] = "Spades";}}(3)public static void main(String args[]) {PlayCard pcard = new PlayCard();for(int i=0;i<13;i++)for(int j=0;j<4;j++)System.out.println(pcard.play(i,j));}第6章1、选择题(1)B (2)B (3)C (4)B (5)D (6)C (7)AB (8)BC2、阅读程序(1)methodFour覆盖了父类的方法(2)mehtodTwo重载了父类的方法(3)6个以上,其中本身4个方法,从ClassA继承了2个方法methodOne,和static methodThree,从Object类继承了几个方法,如Equal等。

Java程序设计课后练习答案

J a v a程序设计课后练习答案Last updated on the afternoon of January 3, 2021《J a v a程序设计》课后练习答案第一章Java概述一、选择题1.(A)是在Dos命令提示符下编译Java程序的命令,(B)是运行Java程序的命令。

A.javacB.javaC.javadocD.javaw2.(D)不是Java程序中有效的注释符号。

ssB. .jarC. .javD. .java二、简答题1、Java的跨平台的含义是什么为什么Java可以跨平台2、Java语言的一个非常重要的特点就是平台无关性。

它是指用Java编写的应用程序编译后不用修改就可在不同的操作系统平台上运行。

Java之所以能平台无关,主要是依靠Java 虚拟机(JVM)来实现的。

JVM是一种抽象机器,它附着在具体操作系统之上,本身具有一套虚机器指令,并有自己的栈、寄存器组等。

Java编程人员在编写完Java程序后,Java编译器将Java源代码文件编译后生成字节码文件(一种与操作系统无关的二进制文件)。

字节码文件通过Java虚拟机(JVM)里的类加载器加载后,经过字节码校验,由解释器解释成当前电脑的操作系统能够识别的目标代码并最终运行。

以下图展示了Java程序从编译到最后运行的完整过程。

3、简述Java语言的特点Java具有以下特点:1)、简单性Java语言的语法规则和C语言非常相似,只有很少一部分不同于C语言,并且Java还舍弃了C语言中复杂的数据类型(如:指针和结构体),因此很容易入门和掌握。

2)、可靠性和安全性Java从源代码到最终运行经历了一次编译和一次解释,每次都有进行检查,比其它只进行一次编译检查的编程语言具有更高的可靠性和安全性。

3)、面向对象Java是一种完全面向的编程语言,因此它具有面向对象编程语言都拥有的封装、继承和多态三大特点。

4)、平台无关和解释执行Java语言的一个非常重要的特点就是平台无关性。

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