JAVA实验7-9+答案
Java语言程序设计编程题(programming exercises)答案第7章

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程序设计(华东交通大学)知到课后答案章节测试2022年

第一章1.编译和运行以下代码的结果为: public class MyMain{ public static voidmain(String argv){ System.out.println("Hello cruel world"); }}答案:编译无错,但运行时指示找不到main方法2.以下哪个是Java应用程序入口的main方法头?答案:public static voidmain(String a[])3.编译Java源程序文件将产生相应的字节码文件,字节码文件的扩展名为?答案:class4.main方法是JavaApplication程序执行的入口点,关于main方法的方法头合法的有?答案:public static void main(String[ ] args);public static voidmain(String arg[ ])5.每个源程序文件中只能定义一个类。
答案:错第二章1.在Java中,十进制数16的十六进制表示格式是?答案:0x102.要产生[10,100]之间的随机整数使用哪个表达式?答案:10+(int)(Math.random()*91)3.下列符号中不能作为Java标识符的是?答案:45six4.下面各项中定义变量及赋值不正确的是?答案:float f = 45.0;5.执行以下代码段后,x,a,和b的值为?intx,a=6,b=7;x=a+++b++;答案:x= 13,a=7, b=86.下列哪个不是Java的保留字?答案:cin7.哪些赋值是合法的?答案: float f = -412;;long test = 012; ;double d =0x12345678;8.下列代码中,将引入编译错误的行是1 public class Exercise{2 public staticvoid main(String args[]){3 float f = 0.0 ;4 f = f + 1.0 ;5 }6 }答案:第3行;第4行9.下列哪些是合法标识符?答案:$persons ;TwoUsers10.下列哪些是java中有效的整数表示形式?答案:022;0x22;22第三章1.如何更改break语句使退出inner和middle循环,继续外循环的下一轮?outer: for (int x = 0; x < 3; x++) {middle: for (int y = 0; y < 3; y++) {inner:for (int z = 0; z < 3; z++) { if (arr(x, y, z) == targetValue) break; } }}答案:breakmiddle;2.以下程序的输出结果为?public class Test { public static void main(Stringargs[]) { for ( int k = 0; k < 3; k++) System.out.print("k"); }}答案:kkk3.以下代码的调试结果为?1: public class Q102: {3: public static voidmain(String[] args)4: {5: int i = 10;6: int j = 10;7: boolean b = false;8: 9: if( b =i == j)10: System.out.println("True");11: else12:System.out.println("False");13: }14: }答案:输出:True4.以下代码的调试结果为?public class test { public static void main(Stringargs[]) { int i = 1; do { i–; } while (i > 2); System.out.println(i); }}答案:05.下面的代码段执行之后count的值是什么? int count = 0; for (int i = 1; i < 4;i++) { count += i; } System.out.println(count);答案:66.以下程序的运行结果为: 1. public class Conditional { 2. public static voidmain(String args [] ) { 3. int x = 4; 4. System.out.println( "value is " + 5. ((x >4) ? 99.99 : 9)); 6. } 7. }答案:输出: value is 9.07.下列程序的运行结果?public class Test { public static void main(String a[]){ int x=3,y=4,z=5; if (x>3) { if (y<2) System.out.println("show one"); elseSystem.out.println("show two"); } else { if (z>4) System.out.println("showthree"); else System.out.println("show four"); } }}答案: show three8.以下程序调试结果public class test { public static void main(String args[]){ int i=1, j=3; while (j>0) { j–; i++; } System.out.println(i); }}答案:49.在switch(expression)语句中,expression的数据类型不能是?答案:boolean;double10.假设a是int类型变量,并初始化为1,则下列哪个为合法的条件语句?答案: if (true) { }; if (a<3) { }第四章1.以下程序运行时输入:javaCyclehellotwome2publicclassCycle{publicstaticvoidmain(Stringargs[]){S ystem.out.println(args[1]);}}则运行结果为?答案:two2.publicclasstest{ publicstaticvoidmain(Stringargs[]){ intm=0;for(intk=0;k<2;k++) method(m++); System.out.println(m); }publicstaticvoidmethod(intm){ System.out.print(m); }答案:0123.以下程序运行结果为:publicclassQ{ publicstaticvoidmain(Stringargv[]){ intanar[]=newint[5];System.out.println(anar[0]); } }答案:04.下列程序的运行结果是:public class Test { public static void main(Stringargs[]) { int m[]={1,2,3,4,5,6,7,8}; int sum = 0; for (int i=0;i<8;i++){ sum =sum + m[i]; if (i==3) break; } System.out.println(sum); }}答案:105.下面定义和给数组初始化正确的是:答案:String temp [] = {''a'', ''b'', ''c''};6.在注释//Start For loop 处要插入哪段代码可以实现根据变量i的值定位访问数组ia[]的所有元素。
JAVA程序设计课后习题及答案7

第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。
java开发实战经典习题答案完整版

Lake·Rothschild 疯狂源自梦想 lake·Rothschild
第八题:有 30 个 0~9 之间的数,分别统计 0~9 这 10 个数分别出现了多少次?
第(7)页 雷克 共(27)页
Lake·Rothschild 疯狂源自梦想 lake·Rothschild 第九题:定义一个整型数组,保存 10 个数据,利用程序完成将最大值保存在数 组中第一个元素的操作。
public void setPrice(float price){ this.price = price;
} public float getPrice(){
return this.price; } public void setNum(int num){
this.num = num; } public int getNum(){
第(10)页 雷克 共(27)页
Lake·Rothschild 疯狂源自梦想 lake·Rothschild
⑥从任意给定的身份证号提取此人的生日
使用正则表达式的方法:
第九题:声明一个图书类,其数据成员为:书名,编号,(利用静态变量实现自动编号)、书 价,并拥有静态数据成员册数,记录图书的总册数,在构造方法中利用此静态变量为对象的 编号赋值,在主方法中定义对象数组,并求出总册数。 class Book {
设计一个生产电脑和搬运电脑类要求生产出一台电脑就搬走一台电脑如果没有新的电脑产生则等待新的电脑产生才能搬运如果电脑没有搬走则不能生产新的电脑最后统计生产出来的电脑的数量
Lake·Rothschild 疯狂源自梦想 lake·Rothschild
Java 开发实战经典课后答案 By 雷克
第三章 第一题:打印 1~1000 范围内的水仙花数,水仙花数是指一个三位数,其各位数 字的立方和等于该数本身。
java习题及答案第9章 习题参考答案

第9章习题解答1.与输入/输出有关的流类有哪些?答:与输入/输出有关的流类主要有InputStream、OutputStream和Reader、Writer类及其子类。
除此以外,与流有关的类还有File类、FileDescriptor类、StreamTokenizer类和RandomAccessFile类。
2.字节流与字符流之间有哪些区别?答:字节流是面向字节的流,流中的数据以8位字节为单位进行读写,是抽象类InputStream和OutputStream的子类,通常用于读写二进制数据,如图像和声音。
字符流是面向字符的流,流中的数据以16位字符(Unicode字符)为单位进行读写,是抽象类Reader和Writer的子类,通常用于字符数据的处理。
3.什么是节点流?什么是处理流或过滤流?分别在什么场合使用?答:一个流有两个端点。
一个端点是程序;另一个端点可以是特定的外部设备(如键盘、显示器、已连接的网络等)和磁盘文件,甚至是一块内存区域(统称为节点),也可以是一个已存在流的目的端。
流的一端是程序,另一端是节点的流,称为节点流。
节点流是一种最基本的流。
以其它已经存在的流作为一个端点的流,称为处理流。
处理流又称过滤流,是对已存在的节点流或其它处理流的进一步处理。
对节点流中的数据只能按字节或字符读写。
当读写的数据不是单个字节或字符,而是一个数据块或字符串等时,就要使用处理流或过滤流。
4.标准流对象有哪些?它们是哪个类的对象?答:标准流对象有3个,它们是:System.in、System.out和System.err。
System.in 是InputStream类对象,System.out和System.err是PrintStream类对象。
5.顺序读写与随机读写的特点分别是什么?答:所谓顺序读写是指在读写流中的数据时只能按顺序进行。
换言之,在读取流中的第n个字节或字符时,必须已经读取了流中的前n-1个字节或字符;同样,在写入了流中n-1个字节或字符后,才能写入第n个字节或字符。
浙江大学Java语言程序设计实验答案全集

Java答案全集实验汇总。
实验2 数据类型和变量的使用一、程序填空,在屏幕上显示一个短句“Programming in Java is fun!”import java.io.*;public class Test10001{public static void main(String args[]){/*------------------------*/}}二、程序填空,在屏幕上显示如下网格。
+---+---+| | || | |+---+---+import java.io.*;public class Test10002{public static void main(String args[]){/*------------------------*/}}三、编写程序,在屏幕上显示如下图案。
(要求:第1行行首无空格,每行行尾无空格)* * * ** * ** **public class Test10003{public static void main(String args[]){/*------------------------*/}}实验3 运算符和表达式的使用1、运行结果:m=2 k=1x=1.0 y=2.0 z=-3.0ch1=-A ch2=Ach1=-A ch2=aHello,Welcome to core Java!思考题:(1)字符'A'的Unicode码比字符'a'的Unicode码小32。
(2)假设字符型变量ch中保存一个大写字母,执行ch+=('a'-'A' );后,ch中是相应的小写字母。
例:若ch='B',执行后ch='b'。
2、运行结果:m=3 n=2. m大于n吗?truem=2 n=2. m大于n吗?falsestr1=Hello;str2=Hello!s1和s2相等吗?false思考题:(1)s2比s1多一个字符“!”,所以不相同。
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来存储对象。
Java面向对象程序设计_习题解答(耿祥义)

书后习题参考答案习题1 2习题2 3习题3 4习题4 10习题5 11习题6 14习题7 15习题9 16习题12 20习题13 25习题14 27习题15 28习题16 31习题17 39习题11.James Gosling2.(1)使用一个文本编辑器编写源文件。
(2)使用Java编译器(javac.exe)编译Java源程序,得到字节码文件。
命令:javac –d . 文件名称.java(3)使用Java解释器(java.exe)运行Java程序。
命令:java 包名.类名3.Java的源文件是由若干个书写形式互相独立的类、接口、枚举等组成。
应用程序中可以没有public类,若有的话至多可以有一个public类。
4.新建JAVA_HOME系统环境变量,指向安装目录在系统环境变量path中增加内容:%JAVA_HOME%\bin;新建系统环境变量classpath并填入三项:.; %JAVA_HOME%\lib\dt.jar; %JAVA_HOME%\lib\tools.jar5. B6. Java源文件的扩展名是.java。
Java字节码的扩展名是.class。
7. D8.(1)Speak.java(2)生成两个字节码文件,这些字节码文件的名字Speak.class和Xiti8.class(3)java Xiti8(4)执行java Speak的错误提示Exception in thread "main" ng.NoSuchMethodError: main执行java xiti8得到的错误提示Exception in thread "main" ng.NoClassDefFoundError: xiti8 (wrong name: Xiti8)执行java Xiti8.class得到的错误提示Exception in thread "main" ng.NoClassDefFoundError:Xiti8/class执行java Xiti8得到的输出结果I'm glad to meet you9.属于操作题,解答略。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
}
第三步:创建主类,在其中的main()方法中创建对象,实现相应的功能。
// X5_3_6.java文件
package p3;
import p2.*;
public class X5_3_6 {//定义主类
public static void main(String[] args) {
…
}
}
【参考程序】
答案略。
实验8
一、选择题
1.关于异常的含义,下列描述中最正确的一个是(D)。
A.程序编译错误B.程序语法错误
C.程序自定义的异常事件D.程序编译或运行时发生的异常事件
【解析】异常就是程序编译或运行时发生的异常事件。
2.自定义异常时,可以通过对下列哪一项进行继承?(C)
A.Error类B.Applet类
实验7
1.编一个程序,包含以下文件。
(1)Shape.java文件,在该文件中定义接口Shape,该接口在shape包中。
属性:PI。
方法:求面积的方法area()。
(2)Circle.java文件,在该文件中定义圆类Circle,该类在circle包中,实现Shape接口。
属性:圆半径radius。
Cylinder cy1 = new Cylinder(27.3,32.7);
Cylinder cy2 = new Cylinder(133.5,155.8);
System.out.println("cy1.area: "+cy1.area());
System.out.println("cy1.volume: "+cy1.volume());
【编程分析】本题主要考察接口、包、继承、封装等问题。编程步骤如下:
第一步:首先创建p1包,在其中创建Shape接口
// Shape.java文件
package p1;//创建p1包
public interface Shape{//定义Shape接口
…
}
第二步:创建Circle类和Cylinder类,它们都定义在p2包中。
// Circle.java文件
package p2;//创建p2包
import p1.*;
public class Circle implements Shape{//定义实现Shape接口的Circle类
…
}
// Cylinder.java文件
package p2;
public class Cylinder extends Circle{//创建继承Circle类的Cylinder类
System.out.println("SubClass constructor");
}
}
public class Test1 {
public static void main(String[] args) {
SubClass descendent = new SubClass();
}
}
4)利用多态性编程,创建一个抽象类shape类,定义一个函数Area为求面积的公共方法,再定义Triangle,Rectangle和circle类,实现computerArea方法;增加display方法,显示name和area,并在Triangle,Rectangle和circle类覆盖该方法,并为每个类增加自己的构造方法;在主类中创建不同对象,求得不同形状的面积。
(4)X5_3_6.java文件,在该文件中定义主类X5_3_6,该类在默认包中,其中包含主方法main(),在主方法中创建两个圆类对象cir1和cir2,具体尺寸自己确定,并显示圆的面积和周长;再创建两个圆柱体类的对象cy1和cy2,具体尺寸自己确定,然后分别显示圆柱体cy1和cy2的底圆的面积和周长以及它们各自的体积和表面积。
System.out.println("cy2.area: "+cy2.area());
System.out.println("cy2.volume: "+cy2.volume());
}
}
// Shape.java文件
package p1;//创建p1包
public interface Shape{//定义Shape接口
public static void main(String[] args) {
// TODO code application logic here
Sum x=new Sum();
x.disp(100);
}
}
3)改错,上传正确答案,并以注释形式给出错误原因
class SuperClass
{
public SuperClass(String msg)
C.throws IOException();D.throws IOException;
【解析】在方法体内抛出异常时只能使用throw,而不能使用throws,另外,“new Exception("")”是创建一个异常,因此B是正确的。
8.下列描述了Java语言通过面相对象的方法进行异常处理的好处,请选出不在这些好处范围之内的一项(C)
public static void main(String[] args) {
try{
return;
}
finally{
System.out.println("Finally");
}
}
}
A.程序正常运行,但不输出任何结果B.程序正常运行,并输出Finally
C.编译通过,但运行时出现异常D.因为没有catch子句,因此不能通过编译
}
public double area(){
return 2*PI*radius*radius+2*PI*radius*height;
}
public double volume(){
return PI*radius*radius*height;
}}Βιβλιοθήκη 2)定义一个接口OneToN,在接口中包含一个抽象方法disp()。定义Sum和Pro类,并分别用不同代码实现ONeToN的disp()方法,在Sum的方法中计算1~n的和,在Pro的方法中计算1~n的乘积
double PI=Math.PI;
double area();//求面积方法
}
// Circle.java文件
package p2;//创建p2包
import p1.*;
public class Circle implements Shape{//定义实现Shape接口的Circle类
double radius;//半径
{ System.out.println("SuperClass constructor: " +msg);}
}
class SubClass extends SuperClass
{
public SubClass(String msg)
{
Super(msg);//父类没有无参的构造方法,应采用super显示调用父类的构造方法
【解析】在执行try-catch-finally语句块时,最后必须执行finally语句块中的内容,而本程序没有异常发生,因此程序正常运行,并输出Finally。
7.下列代码中给出正确的在方法体内抛出异常的是(B)。
A.new throw Exception("");B.throw new Exception("");
}
}
class Pro implements OneToN
{
public void disp(int n)
{
long pro=1;
for(int i=1;i<=n;i++)
{
pro=pro*i;
}
System.out.println(pro);
}
}
public class interfaceTest {
5.运行下面程序时,会产生什么异常?(C)
public classX7_1_5{
public static void main(String[] args) {
int[] z = {1,2,3,4};
int p = z[4];
int x = 0;
int y = 5/x;
}
}
A.ArithmeticExceptionB.NumberFormatException
interface OneToN
{
public void disp(int n);
}
class Sum implements OneToN
{
public void disp(int n)
{
int sum=0;
for(int i=1;i<=n;i++)
{
sum=sum+i;
}
System.out.println(sum);
System.out.println("cir1.area: "+cir1.area());
System.out.println("cir1.perimeter: "+cir1.perimeter());
System.out.println("cir2.area: "+cir2.area());
System.out.println("cir2.perimeter: "+cir2.perimeter());