Java语言程序设计(郑莉)第七章课后习题答案
- 格式:docx
- 大小:99.99 KB
- 文档页数:11
7.1 import java.util.Scanner;public class Exercise01 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter a 4-by-4 matrix row by row:");int[][] matrix = new int[4][4];for (int i = 0; i < 4; i++) {for (int j = 0; j < 4; j++) {matrix[i][j] = input.nextInt();}}System.out.println("Sum of the matrix is " + sumMatrix(matrix));}public static int sumMatrix(int[][] m) {int sum = 0;for (int i = 0; i < m.length; i++) {for (int j = 0; j < m[i].length; j++) {sum += m[i][j];}}return sum;}}7.2 import java.util.Scanner;public class Exercise02 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter a 4-by-4 matrix row by row:");int[][] matrix = new int[4][4];for (int i = 0; i < matrix.length; i ++) {for (int j = 0; j < matrix[i].length; j++) {matrix[i][j] = input.nextInt();}}System.out.println("Sum of the elements in the major diagonal is " + sumMajorDiagonal(matrix));}public static int sumMajorDiagonal(int[][] m) {int sum = 0;for (int i = 0, j = 0; i < m.length && j < m[0].length; i++, j++)sum += m[i][j];return sum;}}7.3 public class Exercise03 {public static void main(String[] args) {//Student's answers to the questionschar[][] answers = {{'A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},{'D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'},{'E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D'},{'C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D'},{'A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},{'B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},{'B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},{'E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}};//Key to the questionschar[] keys = {'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D'};int[][] countOfCorrect = new int[answers.length][2];//Grand all answersfor (int i = 0; i < answers.length; i++) {//Grade one studentint correctCount = 0;for (int j = 0; j < answers[i].length; j++) {if (answers[i][j] == keys[j])correctCount++;}countOfCorrect[i][1] = correctCount;countOfCorrect[i][0] = i;}for (int i = 0; i < countOfCorrect.length; i++) {int currentStudent = countOfCorrect[i][0];int min = countOfCorrect[i][1];int minIndex = i;for (int j = i + 1; j < countOfCorrect.length; j++) {if (countOfCorrect[j][1] < min) {currentStudent = countOfCorrect[j][0];min = countOfCorrect[j][1];minIndex = j;}}if (minIndex != i) {countOfCorrect[minIndex][0] = countOfCorrect[i][0];countOfCorrect[minIndex][1] = countOfCorrect[i][1];countOfCorrect[i][0] = currentStudent;countOfCorrect[i][1] = min;}}for (int j = 0; j < countOfCorrect.length; j++)System.out.println("Student " + countOfCorrect[j][0] + "'s correct count is " + countOfCorrect[j][1]);}}7.4 public class Exercise04 {public static void main(String[] args) {int[][] workHours = {{2, 4, 3, 4, 5, 8, 8},{7, 3, 4, 3, 3, 4, 4},{9, 3, 4, 7, 3, 4, 1},{3, 5, 3, 4, 6, 3, 8},{3, 4, 4, 6, 3, 4, 4},{3, 7, 4, 8, 3, 8, 4},{6, 3, 5, 9, 2, 7, 9}};int[][] totalWorkHours = new int[workHours.length][2];for (int i = 0; i < workHours.length; i++) {int sum = 0;for (int j = 0; j < workHours[i].length; j++) {sum += workHours[i][j];}totalWorkHours[i][0] = i;totalWorkHours[i][1] = sum;}int[][] sortTotalWorkHours = sortArray(totalWorkHours);for (int j = 0; j < sortTotalWorkHours.length; j++)System.out.println("Employee " + sortTotalWorkHours[j][0] + "'s total work hours is " + sortTotalWorkHours[j][1]);}public static int[][] sortArray(int[][] array) {for (int i = 0; i < array.length; i++) {int currentEmployee = array[i][0];int currentMaxWorkHours = array[i][1];int currentMaxIndex = i;for (int j = i + 1; j < array.length; j++) {if (array[j][1] > currentMaxWorkHours) {currentEmployee = array[j][0];currentMaxWorkHours = array[j][1];currentMaxIndex = j;}}if (currentMaxIndex != i) {array[currentMaxIndex][0] = array[i][0];array[currentMaxIndex][1] = array[i][1];array[i][0] = currentEmployee;array[i][1] = currentMaxWorkHours;}}return array;}}7.5 import java.util.Scanner;public class Exercise05 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter a 4-by-4 matrix1:");int[][] matrix1 = new int[4][4];int[][] matrix2 = new int[4][4];for (int i = 0; i < matrix1.length; i++) {for (int j = 0; j < matrix1[i].length; j++)matrix1[i][j] = input.nextInt();}System.out.println("Enter a 4-by-4 matrix2:");for (int i = 0; i < matrix2.length; i++) {for (int j = 0; j < matrix2[i].length; j++)matrix2[i][j] = input.nextInt();}int[][] sumOfMatrix = addMatrix(matrix1, matrix2);printMatrix(matrix1, matrix2, sumOfMatrix);}public static int[][] addMatrix(int[][] a, int[][] b) {int[][] sum = new int[a.length][a[0].length];for (int i = 0; i < a.length; i++) {for (int j = 0; j < a[i].length; j++)sum[i][j] = a[i][j] + b[i][j];}return sum;}public static void printMatrix(int[][] matrix1, int[][] matrix2, int[][] sumOfMatrix) { for (int i = 0; i < matrix1.length; i++) {for (int j = 0; j < matrix1[i].length; j++) {System.out.print((matrix1[i][j] < 10 ? " " : "") + matrix1[i][j] + " ");}if (i != Math.ceil(matrix1.length / 2))System.out.print(" ");elseSystem.out.print("+ ");for (int j = 0; j < matrix2[i].length; j++) {System.out.print((matrix2[i][j] < 10 ? " " : "") + matrix2[i][j] + " ");}if (i != Math.ceil(matrix1.length / 2))System.out.print(" ");elseSystem.out.print("= ");for (int j = 0; j < matrix1[i].length; j++) {System.out.print((sumOfMatrix[i][j] < 10 ? " " : "") + sumOfMatrix[i][j] + "");}System.out.println();}}}7.6 import java.util.Scanner;public class Exercise06 {public static void main(String[] args) {Scanner input = new Scanner(System.in);double[][] matrix1 = new double[3][3];double[][] matrix2 = new double[3][3];System.out.println("Enter a 3-by-3 matrix1:");for (int i = 0; i < matrix1.length; i++) {for (int j = 0; j < matrix1[i].length; j++)matrix1[i][j] = input.nextDouble();}System.out.println("Enter a 3-by-3 matrix2:");for (int i = 0; i < matrix2.length; i++) {for (int j = 0; j < matrix2[i].length; j++)matrix2[i][j] = input.nextDouble();}double[][] multiplyMatrix = multiplyMatrix(matrix1, matrix2);for (int i = 0; i < matrix1.length; i++) {for (int j = 0; j < matrix1[i].length; j++) {System.out.print(matrix1[i][j] + " ");}if (i != Math.ceil(matrix1.length / 2))System.out.print(" ");elseSystem.out.print("* ");for (int j = 0; j < matrix2[i].length; j++) {System.out.print(matrix2[i][j] + " ");}if (i != Math.ceil(matrix1.length / 2))System.out.print(" ");elseSystem.out.print("= ");for (int j = 0; j < matrix1[i].length; j++) {System.out.print((int)(multiplyMatrix[i][j] * 10) / 10.0 + " ");}System.out.println();}}public static double[][] multiplyMatrix(double[][] a, double[][] b) {double[][] multiply = new double[a.length][a[0].length];for (int i = 0; i < a.length; i++) {for (int j = 0; j < multiply[i].length; j++) {for (int m = 0; m < a.length; m++)multiply[i][j] += a[i][m] * b[m][j];}}return multiply;}}7.7 public class Exercise07 {public static void main(String[] args) {double[][] points = {{-1, 0, 3}, {-1, -1, -1}, {4, 1, 1}, {2, 0.5, 9}, {3.5, 2, -1}, {3, 1.5, 3}, {-1.5, 4, 2}, {5.5, 4, -0.5}};//p1 and p2 are the indices in the points arrayint p1 = 0, p2 = 1; //Initial two pointsdouble shortestDistance = distance(points[p1][0], points[p1][1], points[p1][2],points[p2][0], points[p2][1], points[p2][2]); //Initialize shortestDistance//Compute distance for every two pointsfor (int i = 0; i < points.length; i++) {for (int j = i + 1; j < points.length; j++) {double distance = distance(points[i][0], points[i][1], points[i][2],points[j][0], points[j][1], points[j][2]); //Find distanceif (distance < shortestDistance) {p1 = i; //Update p1p2 = j; //Update p2shortestDistance = distance; //Update shortestDistance}}}//Display resultSystem.out.println("The closest two points are " + "(" + points[p1][0] + ", " +points[p1][1] + points[p1][2] + ") and (" +points[p2][0] + ", " + points[p2][1] + points[p2][2] + ")");}public static double distance(double x1, double y1, double z1, double x2, double y2, double z2) {return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) + (z2 - z1) * (z2 - z1));}}7.8 import java.util.Scanner;public class Exercise08 {public static void main(String[] args) {double[][] points = {{-1, 3}, {-1, -1}, {1, 1}, {0, 0.5},{2, 0.5}, {2, -1}, {3, 3}, {4, 2}, {4, -0.5}};//p1 and p2 are the indices in the points arrayint p1 = 0, p2 = 1; //Initial two pointsdouble shortestDistance = distance(points[p1][0], points[p1][1],points[p2][0], points[p2][1]); //Initialize shortestDistanceint[][] indices = new int[points.length][2];int k = 0;indices[k][0] = p1;indices[k][1] = p2;//Compute distance for every two pointsfor (int i = 0; i < points.length; i++) {for (int j = i + 1; j < points.length; j++) {double distance = distance(points[i][0], points[i][1],points[j][0], points[j][1]); //Find distanceif (distance < shortestDistance) {indices[k][0] = i; //Update p1indices[k][1] = j; //Update p2shortestDistance = distance; //Update shortestDistance}else if (distance == shortestDistance) {k++;indices[k][0] = i;indices[k][1] = j;}}}// Display all closest pairsfor (int i = 0; i <= k; i++) {p1 = indices[i][0]; p2 = indices[i][1];System.out.println("The closest two points are " +"(" + points[p1][0] + ", " + points[p1][1] + ") and (" +points[p2][0] + ", " + points[p2][1] + ")");}System.out.println("Their distance is " + shortestDistance);}public static double distance(double x1, double y1, double x2, double y2) { return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));}}7.9 import java.util.Scanner;public class Exercise09 {public static void main(String[] args) {char[][] ticTacToe = new char[3][3];printTable(ticTacToe);enterX(ticTacToe);}/*** Player X to enter X*/public static void enterX(char[][] ticTacToe) {Scanner input = new Scanner(System.in);System.out.print("Enter a row (0, 1 or 2) for player X: ");int rowForX = input.nextInt();System.out.print("Enter a column (0, 1 or 2) for player X: ");int columnForX = input.nextInt();ticTacToe[rowForX][columnForX] = 'X';printTable(ticTacToe);if (status(ticTacToe)) {enterO(ticTacToe);}}/*** Player O to enter O*/public static void enterO(char[][] ticTacToe) {Scanner input = new Scanner(System.in);System.out.print("Enter a row (0, 1 or 2) for player O: ");int rowForO = input.nextInt();System.out.print("Enter a column (0, 1 or 2) for player O: ");int columnForO = input.nextInt();ticTacToe[rowForO][columnForO] = 'O';printTable(ticTacToe);if (status(ticTacToe)) {enterX(ticTacToe);}}/*** Display the board*/public static void printTable(char[][] array) {System.out.println("-------------");for (int i = 0; i < array.length; i++) {System.out.print("|");for (int j = 0; j < array[i].length; j++) {if (array[i][j] == 'X' | array[i][j] == 'O')System.out.print(" " + array[i][j] + " ");elseSystem.out.print(" ");System.out.print("|");}System.out.println();System.out.println("-------------");}}/*** Return false if one player wins or all the cells have been filled, return true if nobody wins */public static boolean status(char[][] array) {//return false if find one row, column or diagonal with all Xs or Osint i = 0, j = 0;while (i < 3 && j < 3) {if (array[i][j] == 'X' || array[i][j] == 'O') {if (i == 0 && j == 0) {if ((array[i][j] == array[i][j + 1] && array[i][j + 1] == array[i][j + 2]) ||(array[i][j] == array[i + 1][j] && array[i + 1][j] == array[i + 2][j]) ||(array[i][j] == array[i + 1][j + 1] && array[i + 1][j + 1] == array[i + 2][j + 2])) {System.out.println("Player " + array[i][j] + " won");return false;}}if (i == 1 && j == 1) {if ((array[i][j] == array[i][j - 1] && array[i][j] == array[i][j + 1]) ||(array[i][j] == array[i - 1][j] && array[i][j] == array[i + 1][j]) ||(array[i][j] == array[i - 1][j + 1] && array[i][j] == array[i + 1][j -1])) {System.out.println("Player " + array[i][j] + " won");return false;}}if (i == 2 && j == 2) {if ((array[i][j] == array[i][j - 1] && array[i][j] == array[i][j - 2]) ||(array[i][j] == array[i - 1][j] && array[i][j] == array[i - 2][j])) {System.out.println("Player " + array[i][j] + " won");return false;}}}i++;j++;}//return true if not all the cells have been filledfor (int m = 0; m < array.length; m++) {for (int n = 0; n < array[m].length; n++) {if (array[m][n] != 'X' && array[m][n] != 'O')return true;}}//return false if all the cells have been filledSystem.out.println("It's a draw");return false;}}7.10 public class Exercise10 {public static void main(String[] args) {int[][] ticTacToe = new int[3][3];for (int i = 0; i < ticTacToe.length; i++) {for (int j = 0; j < ticTacToe[i].length; j++)ticTacToe[i][j] = (int)(Math.random() * 2);}for (int i = 0; i < ticTacToe.length; i++) {for (int j = 0; j < ticTacToe[i].length; j++)System.out.print(ticTacToe[i][j]);System.out.println();}all0sOr1s(ticTacToe);}public static void all0sOr1s(int[][] array) {int i = 0, j = 0;while (i < array.length && j < array.length) {if (i == 0 && j == 0) {if (array[i][j] == array[i][j + 1] && array[i][j + 1] == array[i][j + 2])System.out.println("All " + array[i][j] + "s on row 0");if (array[i][j] == array[i + 1][j] && array[i + 1][j] == array[i + 2][j])System.out.println("All " + array[i][j] + "s on column 0");if (array[i][j] == array[i + 1][j + 1] && array[i + 1][j + 1] == array[i + 2][j + 2])System.out.println("All " + array[i][j] + "s on major diagonal");}if (i == 1 && j == 1) {if (array[i][j] == array[i][j - 1] && array[i][j] == array[i][j + 1])System.out.println("All " + array[i][j] + "s on row 1");if (array[i][j] == array[i - 1][j] && array[i][j] == array[i + 1][j])System.out.println("All " + array[i][j] + "s on column 1");if (array[i][j] == array[i - 1][j + 1] && array[i][j] == array[i + 1][j -1])System.out.println("All " + array[i][j] + "s on sub-diagonal");}if (i == 2 && j == 2) {if (array[i][j] == array[i][j - 1] && array[i][j] == array[i][j - 2])System.out.println("All " + array[i][j] + "s on row 2");if (array[i][j] == array[i - 1][j] && array[i][j] == array[i - 2][j])System.out.println("All " + array[i][j] + "s on column 2");}i++;j++;}}}7.11 import java.util.Scanner;public class Exercise11 {public static void main(String[] args) {//Create a ScannerScanner input = new Scanner(System.in);//Prompt the user to enter a numberSystem.out.print("Enter a number between 0 and 511: ");int number = input.nextInt();//Change the number to binaryint[][] matrix = decimalToBinary(number);//Display the matrix with charactersprintMatrix(matrix);}/*** Change a decimal number to a binary number*/public static int[][] decimalToBinary(int number) {int[][] matrix = new int[3][3];for (int i = matrix.length - 1; i >= 0; i--) {for (int j = matrix[i].length - 1; j >= 0; j--) {matrix[i][j] = number % 2;number = number / 2;}}return matrix;}/*** Print the matrix with characters*/public static void printMatrix(int[][] matrix) {for (int i = 0; i < matrix.length; i++) {for (int j = 0; j < matrix[i].length; j++) {if (matrix[i][j] == 0)System.out.print("H ");if (matrix[i][j] == 1)System.out.print("T ");}System.out.println();}}}7.12 import java.util.Scanner;public class Exercise12 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter the taxable income: ");double income = input.nextDouble();System.out.print("0-single filer, 1-married joinly,\n" +"2-married separately, 3-head of household\n" +"Enter the filing status: ");int status = input.nextInt();System.out.println("Tax is " + (int)(computeTax(income, status) * 100) / 100.0);}public static double computeTax(double income, int status) {double[] rates = {0.10, 0.15, 0.25, 0.28, 0.33, 0.35};int[][] brackets = {{8350, 33950, 82250, 171550, 372950}, //Single filer{16700, 67900, 137050, 208850, 372950}, //Married jointly{8350, 33950, 68525, 104425, 186475}, //Married separately{11950, 45500, 117450, 190200, 372950} //Head of household };double tax = 0;if (status == 0) {if (income <= brackets[0][0])tax = income * rates[0];else if (income <= brackets[0][1])tax = brackets[0][0] * rates[0] +(income - brackets[0][0]) * rates[1];else if (income <= brackets[0][2])tax = brackets[0][0] * rates[0] +(brackets[0][1] - brackets[0][0]) * rates[1] +(income - brackets[0][1]) * rates[2];else if (income <= brackets[0][3])tax = brackets[0][0] * rates[0] +(brackets[0][1] - brackets[0][0]) * rates[1] +(brackets[0][2] - brackets[0][1]) * rates[2] +(income - brackets[0][2]) * rates[3];else if (income <= brackets[0][4])tax = brackets[0][0] * rates[0] +(brackets[0][1] - brackets[0][0]) * rates[1] +(brackets[0][2] - brackets[0][1]) * rates[2] +(brackets[0][3] - brackets[0][2]) * rates[3] +(income - brackets[0][3]) * rates[4];elsetax = brackets[0][0] * rates[0] +(brackets[0][1] - brackets[0][0]) * rates[1] +(brackets[0][2] - brackets[0][1]) * rates[2] +(brackets[0][3] - brackets[0][2]) * rates[3] +(brackets[0][4] - brackets[0][3]) * rates[3] +(income - brackets[0][4]) * rates[5];}if (status == 1) {if (income <= brackets[1][0])tax = income * rates[0];else if (income <= brackets[1][1])tax = brackets[1][0] * rates[0] +(income - brackets[1][0]) * rates[1];else if (income <= brackets[1][2])tax = brackets[1][0] * rates[0] +(brackets[1][1] - brackets[1][0]) * rates[1] +(income - brackets[1][1]) * rates[2];else if (income <= brackets[1][3])tax = brackets[1][0] * rates[0] +(brackets[1][1] - brackets[1][0]) * rates[1] +(brackets[1][2] - brackets[1][1]) * rates[2] +(income - brackets[1][2]) * rates[3];else if (income <= brackets[1][4])tax = brackets[1][0] * rates[0] +(brackets[1][1] - brackets[1][0]) * rates[1] +(brackets[1][2] - brackets[1][1]) * rates[2] +(brackets[1][3] - brackets[1][2]) * rates[3] +(income - brackets[1][3]) * rates[4];elsetax = brackets[1][0] * rates[0] +(brackets[1][1] - brackets[1][0]) * rates[1] +(brackets[1][2] - brackets[1][1]) * rates[2] +(brackets[1][3] - brackets[1][2]) * rates[3] +(brackets[1][4] - brackets[1][3]) * rates[3] +(income - brackets[1][4]) * rates[5];}if (status == 2) {if (income <= brackets[2][0])tax = income * rates[0];else if (income <= brackets[2][1])tax = brackets[2][0] * rates[0] +(income - brackets[2][0]) * rates[1];else if (income <= brackets[2][2])tax = brackets[2][0] * rates[0] +(brackets[2][1] - brackets[2][0]) * rates[1] +(income - brackets[2][1]) * rates[2];else if (income <= brackets[2][3])tax = brackets[2][0] * rates[0] +(brackets[2][1] - brackets[2][0]) * rates[1] +(brackets[2][2] - brackets[2][1]) * rates[2] +(income - brackets[2][2]) * rates[3];else if (income <= brackets[2][4])tax = brackets[2][0] * rates[0] +(brackets[2][1] - brackets[2][0]) * rates[1] +(brackets[2][2] - brackets[2][1]) * rates[2] +(brackets[2][3] - brackets[2][2]) * rates[3] +(income - brackets[2][3]) * rates[4];elsetax = brackets[2][0] * rates[0] +(brackets[2][1] - brackets[2][0]) * rates[1] +(brackets[2][2] - brackets[2][1]) * rates[2] +(brackets[2][3] - brackets[2][2]) * rates[3] +(brackets[2][4] - brackets[2][3]) * rates[3] +(income - brackets[2][4]) * rates[5];}if (status == 3) {if (income <= brackets[3][0])tax = income * rates[0];else if (income <= brackets[3][1])tax = brackets[3][0] * rates[0] +(income - brackets[3][0]) * rates[1];else if (income <= brackets[3][2])tax = brackets[3][0] * rates[0] +(brackets[3][1] - brackets[3][0]) * rates[1] +(income - brackets[3][1]) * rates[2];else if (income <= brackets[3][3])tax = brackets[3][0] * rates[0] +(brackets[3][1] - brackets[3][0]) * rates[1] +(brackets[3][2] - brackets[3][1]) * rates[2] +(income - brackets[3][2]) * rates[3];else if (income <= brackets[3][4])tax = brackets[3][0] * rates[0] +(brackets[3][1] - brackets[3][0]) * rates[1] +(brackets[3][2] - brackets[3][1]) * rates[2] +(brackets[3][3] - brackets[3][2]) * rates[3] +(income - brackets[3][3]) * rates[4];elsetax = brackets[3][0] * rates[0] +(brackets[3][1] - brackets[3][0]) * rates[1] +(brackets[3][2] - brackets[3][1]) * rates[2] +(brackets[3][3] - brackets[3][2]) * rates[3] +(brackets[3][4] - brackets[3][3]) * rates[3] +(income - brackets[3][4]) * rates[5];}return tax;}}7.13 import java.util.Scanner;public class Exercise13 {public static void main(String[] args) {//Create a ScannerScanner input = new Scanner(System.in);//Prompt the user to enter the number of rows and columns of the arraySystem.out.print("Enter the number of rows and columns of the array: ");int rows = input.nextInt();int columns = input.nextInt();//Prompt the user to enter the arraySystem.out.println("Enter the array:");double[][] array = new double[rows][columns];for (int i = 0; i < array.length; i++) {for (int j = 0; j < array[i].length; j++)array[i][j] = input.nextDouble();}//Display the location of the largest element in the arrayint[] location = findLocation(array);System.out.println("The location of the largest element is at (" + location[0] + ", " + location[1] + ")");}/*** Return the location of the largest element in the array*/public static int[] findLocation(double[][] array) {//Assume array[0][0] is the largest elementdouble largest = array[0][0];int[] location = {0, 0};//Repeatedly find the largest elementfor (int i = 0; i < array.length; i++) {for (int j = 0; j < array[i].length; j++) {if (array[i][j] > largest) {largest = array[i][j];location[0] = i;location[1] = j;}}}return location;}}7.14 import java.util.Scanner;public class Exercise14 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter the size of the matrix: ");int size = input.nextInt();int[][] matrix = new int[size][size];for (int i = 0; i < matrix.length; i++) {for (int j = 0; j < matrix[i].length; j++)matrix[i][j] = (int)(Math.random() * 2);}printMatrix(matrix);find0sAnd1s(matrix);}public static void printMatrix(int[][] array) {for (int i = 0; i < array.length; i++) {for (int j = 0; j < array[i].length; j++)System.out.print(array[i][j]);System.out.println();}}public static void find0sAnd1s(int[][] array) {int i = 0, j= 0;int countRow = 0, countColumn = 0, countMajorDiagonal = 0;while (i < array.length && j < array.length) {int a = array[0][0];int b = array[i][j];for (int n = 0; n < array.length; n++) {if (array[i][n] != b)break;else {if (n == array.length - 1) {System.out.println("All " + b + "s on row " + i);countRow++;}}}for (int n = 0; n < array.length; n++) {if (array[n][j] != b)break;else {if (n == array.length - 1) {System.out.println("All " + b + "s on column " + j);countColumn++;}}}if (b != a)countMajorDiagonal++;i++;j++;}if (countRow == 0)System.out.println("No same numbers on a row");if (countColumn == 0)System.out.println("No same number on a column");if (countMajorDiagonal == 0)System.out.println("All " + array[0][0] + "s on the major diagonal");if (countMajorDiagonal > 0)System.out.println("No same numbers on the major diagonal");for (int p = 1, q = array.length - 2; p < array.length && q >= 0; p++, q--) {if (array[p][q] != array[0][array.length - 1]) {System.out.println("No same numbers on the sub-diagonal");break;}else {if (p == array.length - 1 && q == 0)System.out.println("All " + array[0][array.length - 1] + "s on the sub-diagonal");}}}}7.15 public class Exercise15 {public static void main(String[] args) {double[][] set1 = {{-1, -1}, {2, 2}, {3, 3}, {4, 4}};double[][] set2 = {{0, 1}, {1, 2}, {4, 5}, {5, 6}};double[][] set3 = {{0, 1}, {1, 2}, {4, 5}, {4.5, 4}};System.out.println("Is set1 on the same line? " + isOnSameLine(set1));。
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语言程序设计第七章课后习题答案1.数组的声明与数组元素的创建有什么关系?答:声明数组仅仅是代表试图创建数组,不分配任何存储空间,声明是为创建做“铺垫”。
2.Vector类的对象与数组有什么关系?什么时候适合使用数组,什么时候适合使用Vector?答:vector是一个能够存放任意对象类型的动态数组,容量能自动扩充,而数组存储固定且类型相同的对象;对于存储固定类型相同的对象使用数组,对于存储不同类型或者动态调整数组大小的情况使用Vector。
3.与顺序查找相比,二分查找有什么优势?使用二分查找的条件?答:对于大数据量中进行查找时二分查找比顺序查找效率高得多;条件是已排序的数组。
4.试举出三种常见的排序算法,并简单说明其排序思路。
答:①选择排序:基本思想是站在未排序列中选一个最小元素,作为已排序子序列,然后再重复地从未排序子序列中选取一个最小元素,把它加到已经排序的序列中,作为已排序子序列的最后一个元素,直到把未排序列中的元素处理完为止。
②插入排序:是将待排序的数据按一定的规则逐一插入到已排序序列中的合适位置处,直到将全部数据都插入为止。
③二分查找:将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。
重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。
5.声明一个类People,成员变量有姓名、出生日期、性别、身高、体重等;生成10个People 类对象,并放在一个以为数组中,编写方法按身高进行排序。
//People类public class People{private String name;private String birthdaydate;private String sex;private double height;private double weight;public People(){//默认构造函数}public People(People p){=;this.birthdaydate=p.birthdaydate;this.sex=p.sex;this.height=p.height;this.weight=p.weight;}public People(String name,String birthdaydate,String sex,double height,double weight){=name;this.birthdaydate=birthdaydate;this.sex=sex;this.height=height;this.weight=weight;}public String getName() {return name;}public void setName(String name) { = name;}public String getBirthdaydate() {return birthdaydate;}public void setBirthdaydate(String birthdaydate) {this.birthdaydate = birthdaydate;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public double getHeight() {return height;}public void setHeight(double height) {this.height = height;}public double getWeight() {return weight;}public void setWeight(double weight) {this.weight = weight;}public String toString(){return"姓名:"+name+"\n出生年月:"+birthdaydate+"\n性别:"+sex+"\n 身高:"+height+"\n体重:"+weight;}}//test7_5类public class test7_5 {/***@param args*/public static void main(String[] args) {// TODO Auto-generated method stubPeople[] people={new People("林楚金","1989年8月13日","男",182,63.5),new People("诸葛亮","181年7月23日","男",184,76.6),new People("迈克杰克逊","1958年8月29日","男",180,60),new People("乔丹","1963年2月17日","男",198,98.1),new People("拿破仑","1769年8月15日","男",159.5,63),new People("苍井空","1983年11月11日","女",155,45),};People temp=new People();for(int i=0;i<people.length-1;i++)for(int j=i+1;j<people.length;j++){if(people[i].getHeight()<people[j].getHeight()){temp=people[j];people[j]=people[i];people[i]=temp;}}System.out.println("按身高从小到大排序后的结果如下:");for(int i=0;i<people.length;i++)System.out.println(people[i]+"\n");}}运行结果:6.声明一个类,此类使用私有的ArrayList来存储对象。
《J a v a程序设计》课后练习答案第一章Java概述一、选择题1.( A )是在Dos命令提示符下编译Java程序的命令,( B )是运行Java程序的命令。
A.javacB.javaC.javadocD.javaw2.( D )不是Java程序中有效的注释符号。
A.//B.C.D.3.(A.B.C.D.4.JavaA.B.C.D.5.JavaA.1、JavaJava(JVM)Java以下图展示了Java程序从编译到最后运行的完整过程。
2、简述Java语言的特点Java具有以下特点:1)、简单性Java语言的语法规则和C语言非常相似,只有很少一部分不同于C语言,并且Java还舍弃了C语言中复杂的数据类型(如:指针和结构体),因此很容易入门和掌握。
2)、可靠性和安全性Java从源代码到最终运行经历了一次编译和一次解释,每次都有进行检查,比其它只进行一次编译检查的编程语言具有更高的可靠性和安全性。
3)、面向对象Java是一种完全面向的编程语言,因此它具有面向对象编程语言都拥有的封装、继承和多态三大特点。
4)、平台无关和解释执行Java语言的一个非常重要的特点就是平台无关性。
它是指用Java编写的应用程序编译后不用修改就可在不同的操作系统平台上运行。
Java之所以能平台无关,主要是依靠Java虚拟机(JVM)来实现的。
Java编译器将Java源代码文件编译后生成字节码文件(一种与操作系统无关的二进制文件)5)、6)、Java来。
1、/****/}}第二章Java语法基础一、选择题1.下面哪个单词是Java语言的关键字( B )?A. DoubleB. thisC. stringD. bool2.下面属于Java关键字的是( D )。
A. NULLB. IFC. DoD. goto3.在启动Java应用程序时可以通过main( )方法一次性地传递多个参数。
如果传递的参数有多个,可以用空格将这些参数分割;如果某一个参数本身包含空格,可以使用( B )把整个参数引起来。
第7章1.Swing是一个用于开发Java应用程序界面的工具包,它以抽象窗口工具包(abstract window toolkit,AWT)为基础,使跨平台应用程序可以使用任何可插拔的外观风格。
只用很少的代码就可以利用Swing丰富、灵活的功能和模块化组件来创建优雅的用户界面。
也可以这样说,Swing是Java平台的UI(user interface),充当了处理用户与计算机之间全部交互的角色。
相对于AWT来说,Swing的主要优势就在于MVC体系结构的普遍使用。
因为为了简化组件的设计工作,在Swing组件中,视图和控件两部分被合为一体。
每个组件都有一个相关的分离模型和它使用的界面(包括视图和控件)。
2.Swing组件从功能上可以按下面的类型来划分。
(1)顶层容器:如JFrame、JApplet、JDialog、JWindow。
(2)中间容器:如JPanel、JScrollPane、JSplitPane、JToolBar。
(3)特殊容器:在GUI上起特殊作用的中间层,如JInternalFrame、JLayeredPane、JRootPane。
(4)基本控件:实现人机交互的组件,如JButton、JComboBox、JList、JMenu、JSlider、JTextField。
(5)不可编辑信息的显示:向用户显示不可编辑信息的组件,如JLabel、JProgressBar、ToolTip。
(6)可编辑信息的显示:向用户显示可被编辑的格式化信息的组件,如JColorChooser、JFileChooser、JTable、JTextArea。
3.(1)面板(JPanel)。
面板是一个轻量级容器组件,用于容纳界面元素,以便在布局管理器的设置下容纳更多的组件,实现容器的嵌套。
JPanel、JScrollPane、JSplitPane和JInternalFrame都属于常用的中间容器,都是轻量级组件。
JPanel的默认布局管理器是FlowLayout。
习题23.使用“= =”对相同内容的字符串进行比较,看会产生什么样的结果。
答:首先创建一个字符串变量有两种方式:String str = new String("abc");String str = "abc";使用“= =”会因为创建的形式不同而产生不同的结果:String str1 = "abc";String str2 = "abc";System.out.println(str1= =str2); //trueString str1 = new String("abc"); String str2 = "abc";System.out.println(str1= =str2); //falseString str1 = new String("abc"); String str2 = new String("abc"); System.out.println(str1= =str2); //false因此自符串如果是对内容进行比较,使用equals方法比较可靠。
String str1 = "abc";String str2 = "abc";System.out.println(str1= =str2); //trueString str1 = new String("abc"); String str2 = "abc";System.out.println(str1.equals(str2)); //trueString str1 = new String("abc"); String str2 = new String("abc"); System.out.println(str1.equals(str2)); //true5.编写一个程序,把变量n的初始值设置为1678,然后利用除法运算和取余运算把变量的每位数字都提出来并打印,输出结果为:n=1678。
C语言程序设计(郑莉)课后习题答案C++语言程序设计(清华大学郑莉)课后习题答案第一章概述1-1 简述计算机程序设计语言的发展历程。
解:迄今为止计算机程序设计语言的发展经历了机器语言、汇编语言、高级语言等阶段,C++语言是一种面向对象的编程语言,也属于高级语言。
1-2 面向对象的编程语言有哪些特点?解:面向对象的编程语言与以往各种编程语言有根本的不同,它设计的出发点就是为了能更直接的描述客观世界中存在的事物以及它们之间的关系。
面向对象的编程语言将客观事物看作具有属性和行为的对象,通过抽象找出同一类对象的共同属性(静态特征)和行为(动态特征),形成类。
通过类的继承与多态可以很方便地实现代码重用,大大缩短了软件开发周期,并使得软件风格统一。
因此,面向对象的编程语言使程序能够比较直接地反问题域的本来面目,软件开发人员能够利用人类认识事物所采用的一般思维方法来进行软件开发。
C++语言是目前应用最广的面向对象的编程语言。
1-3 什么是结构化程序设计方法?这种方法有哪些优点和缺点?解:结构化程序设计的思路是:自顶向下、逐步求精;其程序结构是按功能划分为若干个基本模块;各模块之间的关系尽可能简单,在功能上相对独立;每一模块内部均是由顺序、选择和循环三种基本结构组成;其模块化实现的具体方法是使用子程序。
结构化程序设计由于采用了模块分解与功能抽象,自顶向下、分而治之的方法,从而有效地将一个较复杂的程序系统设计任务分解成许多易于控制和处理的子任务,便于开发和维护。
虽然结构化程序设计方法具有很多的优点,但它仍是一种面向过程的程序设计方法,它把数据和处理数据的过程分离为相互独立的实体。
当数据结构改变时,所有相关的处理过程都要进行相应的修改,每一种相对于老问题的新方法都要带来额外的开销,程序的可重用性差。
由于图形用户界面的应用,程序运行由顺序运行演变为事件驱动,使得软件使用起来越来越方便,但开发起来却越来越困难,对这种软件的功能很难用过程来描述和实现,使用面向过程的方法来开发和维护都将非常困难。
Java语言程序设计课后习题答案全集Java语言程序设计是一门广泛应用于软件开发领域的编程语言,随着其应用范围的不断扩大,对于掌握Java编程技巧的需求也逐渐增加。
为了帮助读者更好地掌握Java编程,本文将提供Java语言程序设计课后习题的全集答案,供读者参考。
一、基础知识题1. 代码中的注释是什么作用?如何使用注释.答:注释在代码中是用来解释或者说明代码的功能或用途的语句,编译器在编译代码时会自动忽略注释。
在Java中,有三种注释的方式:- 单行注释:使用"// " 可以在代码的一行中加入注释。
- 多行注释:使用"/* */" 可以在多行中添加注释。
- 文档注释:使用"/** */" 可以添加方法或类的文档注释。
2. 什么是Java的数据类型?请列举常见的数据类型。
答:Java的数据类型用来指定变量的类型,常见的数据类型有:- 基本数据类型:包括整型(byte、short、int、long)、浮点型(float、double)、字符型(char)、布尔型(boolean)。
- 引用数据类型:包括类(class)、接口(interface)、数组(array)等。
二、代码编写题1. 编写Java程序,输入两个整数,求和并输出结果。
答:```javaimport java.util.Scanner;public class SumCalculator {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入第一个整数:");int num1 = scanner.nextInt();System.out.print("请输入第二个整数:");int num2 = scanner.nextInt();int sum = num1 + num2;System.out.println("两个整数的和为:" + sum);}}```三、综合应用题1. 编写Java程序,实现学生信息管理系统,要求包括以下功能:- 添加学生信息(姓名、年龄、性别、学号等);- 修改学生信息;- 删除学生信息;- 查询学生信息。
Java语言程序设计第七章课后习题答案1.数组的声明与数组元素的创建有什么关系?答:声明数组仅仅是代表试图创建数组,不分配任何存储空间,声明是为创建做“铺垫”。
2.Vector类的对象与数组有什么关系?什么时候适合使用数组,什么时候适合使用Vector?答:vector是一个能够存放任意对象类型的动态数组,容量能自动扩充,而数组存储固定且类型相同的对象;对于存储固定类型相同的对象使用数组,对于存储不同类型或者动态调整数组大小的情况使用Vector。
3.与顺序查找相比,二分查找有什么优势?使用二分查找的条件?答:对于大数据量中进行查找时二分查找比顺序查找效率高得多;条件是已排序的数组。
4.试举出三种常见的排序算法,并简单说明其排序思路。
答:①选择排序:基本思想是站在未排序列中选一个最小元素,作为已排序子序列,然后再重复地从未排序子序列中选取一个最小元素,把它加到已经排序的序列中,作为已排序子序列的最后一个元素,直到把未排序列中的元素处理完为止。
②插入排序:是将待排序的数据按一定的规则逐一插入到已排序序列中的合适位置处,直到将全部数据都插入为止。
③二分查找:将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。
重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。
5.声明一个类People,成员变量有姓名、出生日期、性别、身高、体重等;生成10个People 类对象,并放在一个以为数组中,编写方法按身高进行排序。
//People类public class People{private String name;private String birthdaydate;private String sex;private double height;private double weight;public People(){//默认构造函数}public People(People p){=;this.birthdaydate=p.birthdaydate;this.sex=p.sex;this.height=p.height;this.weight=p.weight;}public People(String name,String birthdaydate,String sex,double height,double weight){=name;this.birthdaydate=birthdaydate;this.sex=sex;this.height=height;this.weight=weight;}public String getName() {return name;}public void setName(String name) { = name;}public String getBirthdaydate() {return birthdaydate;}public void setBirthdaydate(String birthdaydate) {this.birthdaydate = birthdaydate;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public double getHeight() {return height;}public void setHeight(double height) {this.height = height;}public double getWeight() {return weight;}public void setWeight(double weight) {this.weight = weight;}public String toString(){return"姓名:"+name+"\n出生年月:"+birthdaydate+"\n性别:"+sex+"\n 身高:"+height+"\n体重:"+weight;}}//test7_5类public class test7_5 {/***@param args*/public static void main(String[] args) {// TODO Auto-generated method stubPeople[] people={new People("林楚金","1989年8月13日","男",182,63.5),new People("诸葛亮","181年7月23日","男",184,76.6),new People("迈克杰克逊","1958年8月29日","男",180,60),new People("乔丹","1963年2月17日","男",198,98.1),new People("拿破仑","1769年8月15日","男",159.5,63),new People("苍井空","1983年11月11日","女",155,45),};People temp=new People();for(int i=0;i<people.length-1;i++)for(int j=i+1;j<people.length;j++){if(people[i].getHeight()<people[j].getHeight()){temp=people[j];people[j]=people[i];people[i]=temp;}}System.out.println("按身高从小到大排序后的结果如下:");for(int i=0;i<people.length;i++)System.out.println(people[i]+"\n");}}运行结果:6.声明一个类,此类使用私有的ArrayList来存储对象。
使用一个Class类的引用得到第一个对象的类型之后,只允许用户插入这种类型的对象。
// Fuck类import java.util.ArrayList;public class Fuck {private ArrayList man=new ArrayList();private Class classType=null;public void add(Object f){if(man.size()==0){classType=f.getClass();}if(classType.equals(f.getClass())){man.add(f);System.out.println("插入成功.");}else{System.out.println("只允许插入"+getClassType()+"类的对象.");}}public ArrayList getMan() {return man;}public Class getClassType() {return classType;}public Fuck(){}}//test7_6public class test7_6 {public static void main(String[] args) {Fuck fuckman=new Fuck();String s=new String("林楚金");fuckman.add(s);fuckman.add(10);//测试插入插入整数fuckman.add('f');//测试插入插入字符fuckman.add("希特勒");System.out.println(fuckman.getMan());}}运行结果:7.找出一个二维数组的鞍点,即该位置上的元素在所在行上最大,在所在列上最小。
(也可能没有鞍点)//test7_7import java.util.Scanner;public class test7_7 {public static void main(String[] args) {int row, series, max;boolean T=false;Scanner cin = new Scanner(System.in);System.out.println("请输入数组的行数");row = cin.nextInt();System.out.println("请输入数组的列数");series = cin.nextInt();int[][] Array = new int[row][series];int[] R = new int[row];// 记录每行最大的数的列标int[] S = new int[series];// 记录每列最小的数的行标System.out.println("请输入数组内容");for (int i = 0; i < Array.length; i++)for (int j = 0; j < Array[i].length; j++){ Array[i][j] = cin.nextInt();if(j==series-1) {max = Array[i][0];for (int z = 1; z < series; z++)if (Array[i][z] > max){max = Array[i][z];R[i] = z;}}}for (int j = 0; j < Array[0].length; j++) {max = Array[0][j];for (int z = 1; z < row ; z++)if (Array[z][j] < max){max = Array[z][j];S[j] = z;}}for(int i=0;i<Array.length;i++){if(S[R[i]]==i){System.out.println("鞍点:"+"Array["+i+"]["+R[i]+ "]:"+Array[i][R[i]]+"\n");T=true;}}if(T==false)System.out.println("没有鞍点");}}运行结果:8. 声明一个矩阵类Matrix,其成员变量是一个二维数组,数组元素类型为int,设计下面的方法,并声明测试类对这些方法进行测试。