java 作业七
- 格式:doc
- 大小:165.50 KB
- 文档页数:13
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第七周作业第一部分:介绍翁凯1. 翁凯是一名资深的软件工程师,拥有丰富的开发经验和扎实的编程基础。
2. 他在互联网行业工作多年,曾在多家知名互联网企业担任重要技术职位。
3. 翁凯擅长Java编程,对Java技术有深入的理解和丰富的实战经验。
第二部分:Java第七周作业1. 作业内容:翁凯的Java第七周作业主要包括以下几个部分:面向对象编程、异常处理、多线程编程等。
2. 面向对象编程:翁凯在作业中通过设计类和对象的方式,实现了对现实世界问题的建模和求解。
他充分运用了面向对象的特性,如封装、继承和多态,使得代码结构清晰、逻辑严谨。
3. 异常处理:在作业中,翁凯充分考虑了程序可能出现的异常情况,并进行了相应的处理。
他使用try-catch-finally语句块,对可能出现的异常进行捕获和处理,保证了程序的稳定性和可靠性。
4. 多线程编程:翁凯在作业中还涉及了多线程编程的内容,他充分利用Java提供的多线程机制,实现了并发执行的效果,提高了程序的性能和响应速度。
第三部分:作业优点和亮点1. 作业的优点:翁凯的作业在代码逻辑上清晰,结构上合理,且符合面向对象编程的思想和规范。
他的异常处理能力较强,程序健壮性良好。
在多线程编程方面,翁凯能够合理运用多线程技术,提高程序的运行效率,体现了他在并发编程方面的能力。
2. 作业的亮点:翁凯在作业中展现了对Java编程语言的深刻理解和熟练应用,尤其是对面向对象编程和多线程编程方面的技术。
他的作业不仅能够完成基本的功能需求,还体现了一定的创新和扩展能力,展现了优秀的编程思维和能力。
第四部分:总结1. 翁凯的Java第七周作业展现了他优秀的编程能力和技术功底。
他在作业中展现了对面向对象编程、异常处理和多线程编程等方面的深入理解和熟练应用,展现了一名优秀软件工程师应有的专业素养和技术水平。
期待翁凯在以后的学习和工作中继续发挥自己的优势,取得更好的成绩和进步。
一、选择题1、以下关于对象的说法不正确的是(D )。
A 组成客观世界(事物)的不同实体可以看成是对象B 对象是一个具有封装性和信息隐藏的独立模块C 对象可以分解和组合,还可以通过相似性原理进行分类和抽象D对象可以更好地模拟计算机的工作方式,体现计算机运行规律,提高程序执行效率。
2、面向对象的特点主要概括为( C )。
A可分解性、可组合性、可分类性B继承性、封装性和多态性C抽象性、继承性、封装性和多态性D封装性、易维护性、可扩展性、可重用性3、以下论述不正确的是(C )。
A对象变量时对象的一个引用B对象是类的一个实例C一个对象可以作为另一个对象的数据成员D对象不可以作为函数的参数传递4、对象之间的继承关系是(D )。
A has-aB is-aC use-aDof-a5、以下Bridge与Road之间是(D )关系。
class Bridge{Road road;}class Road{String name;}A has-aB is-aC use-aD f-a6、要使某个类能被同一个包中的其他类访问,但不能被这个包以外的类访问,可以(A )。
A让该类不使用任何关键字B使用private关键字C 使用final关键字D使用protected关键字7、Java中最基本的类是(D )。
A WindowB ComponentC ObjectD Class8、以下代码将在屏幕上显示的是字符(C )。
Boolean b1=new Boolean(true);Boolean b2=new Boolean(true);if(b1==b2)if(b1.equals(b2))System.out.println("a");elseSystem.out.println("b");elseif(b1.equals(b2))System.out.println("c");elseSystem.out.println("d");A aB bC cD d9、分析以下程序的运行结果,得到的结论是( D )public class MyClass {String s;public static void main(String[] args) { MyClass m=new MyClass();m.go();}void MyClass(){s="constructor";}void go(){System.out.println(s);}}A 程序可以运行,但屏幕没有输出任何字符。
java平时作业作业一:/第二章75页1)找出一个二维数组的鞍点,即该位置上的元素在该行上最大、在列上最小(也可能没有鞍点)。
public class ArrayMaxMin{public static void main(String[] args){inti,j,k,l,g;inttwo_array[][]={{10,6,5},{1,2,4},{16,7,11}};for(i=0;i<two_array.length;i++)< p="">for(j=0;j<two_array[0].length;j++){< p="">l=0;g=0;for(k=0;k<two_array[0].length;k++)< p="">if(two_array[i][j]>two_array[i][k])++l;if(l==two_array[0].length-1){for(k=0;k<two_array.length;k++)< p="">if(two_array[i][j]<two_array[k][j])< p="">++g;if(g==two_array.length-1)System.out.println("该二维数组的鞍点为:two_array["+(i+1)+"]"+"["+(j+1)+"]"+"="+two_array[i][j]);}}}}2)编程验证歌德巴赫猜想,任何大于6的偶数可以表示为两素数之和,如10=3+7。
public class GoldbachGuess{public static void main(String args[]){inti,j,k,l,m,n=50;for(i=8;i<="">if (i%2==0)for(j=2;j<i;j++){< p="">for(l=1,m=0;l<=j;l++)if(j%l==0)m=m+1;if(m==2){k=i-j;for(l=1,m=0;l<=k;l++)if(k%l==0)m=m+1;if(m==2)System.out.println(i+"="+j+"+"+k+" ");}}}}作业二:例3-8/第三章187页对银行帐户类BankAccount进行一系列修改和测试声明BankAccount类声明toString()方法声明存取款方法使用DecimalFormat类声明类方法生成特殊的实例声明类变量作业三:/第四章122页编写java程序,程序中有一个父类Telephone,类中包含电话品牌、电话号码、通话时间、费率等属性,以及计算话费和显示信息等方法;程序中还有一个子类Mobilephone,除了具有Telephone类的属性外,还有自己的属性如网络类型、被叫时间,同时它有自己的计算话费和显示信息的方法。
java作业题编写一个Java程序,实现一个简单的学生信息管理系统。
1. 学生类(Student)- 属性:学号、姓名、性别、年龄、班级- 方法:构造方法、获取和设置属性的方法、重写toString方法以便打印学生信息2. 学生管理类(StudentManager)- 属性:学生列表(使用ArrayList<Student>保存学生信息)- 方法:添加学生、删除学生、通过学号查询学生、通过姓名查询学生、打印所有学生信息3. 主程序(Main)- 创建一个学生管理对象- 在主程序中提供菜单供用户选择操作,选择不同的操作后调用学生管理类中相应的方法- 添加学生:输入学生信息(学号、姓名、性别、年龄、班级),将学生对象添加至学生列表中- 删除学生:输入学号,查找并删除相应的学生- 通过学号查询学生:输入学号,查找并打印学生信息- 通过姓名查询学生:输入姓名,查找并打印学生信息- 打印所有学生信息:遍历学生列表,打印所有学生信息以下是示例代码:```javaimport java.util.ArrayList;import java.util.Scanner;// 学生类class Student {private int id;private String name;private String gender;private int age;private String className;// 构造方法public Student(int id, String name, String gender, int age, String className) {this.id = id; = name;this.gender = gender;this.age = age;this.className = className;}// 获取学生信息public int getId() {return id;}public String getName() {return name;}public String getGender() {return gender;}public int getAge() {return age;}public String getClassName() {return className;}// 设置学生信息public void setId(int id) {this.id = id;}public void setName(String name) { = name;}public void setGender(String gender) {this.gender = gender;}public void setAge(int age) {this.age = age;}public void setClassName(String className) {this.className = className;}// 重写toString方法@Overridepublic String toString() {return "学号: " + id + ", 姓名: " + name + ", 性别: " + gender + ", 年龄: " + age + ", 班级: " + className;}}// 学生管理类class StudentManager {private ArrayList<Student> students;public StudentManager() {students = new ArrayList<>();}// 添加学生public void addStudent(Student student) {students.add(student);System.out.println("添加学生成功!");}// 删除学生public void removeStudent(int id) {// 查找学生Student student = findStudentById(id);if (student != null) {students.remove(student);System.out.println("删除学生成功!");} else {System.out.println("未找到学生!");}}// 通过学号查询学生public void findStudentById() {Scanner scanner = new Scanner(System.in); System.out.println("请输入学号: ");int id = scanner.nextInt();Student student = findStudentById(id);if (student != null) {System.out.println(student);} else {System.out.println("未找到学生!");}}// 通过姓名查询学生public void findStudentByName() {Scanner scanner = new Scanner(System.in); System.out.println("请输入姓名: ");String name = scanner.nextLine();Student student = findStudentByName(name); if (student != null) {System.out.println(student);} else {System.out.println("未找到学生!");}}// 打印所有学生信息public void printAllStudents() {for (Student student : students) {System.out.println(student);}}// 根据学号查找学生private Student findStudentById(int id) {for (Student student : students) {if (student.getId() == id) {return student;}}return null;}// 根据姓名查找学生private Student findStudentByName(String name) { for (Student student : students) {if (student.getName().equals(name)) {return student;}}return null;}}// 主程序public class Main {public static void main(String[] args) {StudentManager studentManager = new StudentManager(); Scanner scanner = new Scanner(System.in);while (true) {System.out.println("学生信息管理系统菜单:");System.out.println("1. 添加学生");System.out.println("2. 删除学生");System.out.println("3. 通过学号查询学生");System.out.println("4. 通过姓名查询学生");System.out.println("5. 打印所有学生信息");System.out.println("0. 退出系统");System.out.println("请选择操作:");int option = scanner.nextInt();switch (option) {case 1:System.out.println("请输入学号: ");int id = scanner.nextInt();System.out.println("请输入姓名: ");String name = scanner.next();System.out.println("请输入性别: ");String gender = scanner.next();System.out.println("请输入年龄: ");int age = scanner.nextInt();System.out.println("请输入班级: ");String className = scanner.next();Student student = new Student(id, name, gender, age, className);studentManager.addStudent(student);break;case 2:System.out.println("请输入学号: ");int deleteId = scanner.nextInt();studentManager.removeStudent(deleteId);break;case 3:studentManager.findStudentById();break;case 4:studentManager.findStudentByName();break;case 5:studentManager.printAllStudents();break;case 0:System.exit(0);default:System.out.println("无效操作!");break;}}}}```运行程序,可以通过菜单进行学生信息的添加、删除、查询和打印等操作。
H a r b i n I n s t i t u t e o f T e c h n o l o g y课程设计报告课程名称: JAVA网络设计设计题目:扫雷游戏院系:电子班级:08设计者:学号:指导教师:辛明影设计时间: 2010,11,29一,题目分析扫雷游戏分析:●扫雷的基本原理九宫格中(3*3共九个格子),中间的数字代表其周围的地雷个数,即以中间数为中心所在地九格中共有中间那个数的地雷。
比如中间为1,那么以这个1为中心,其周围共八个空格中只有一个是地雷。
●扫雷的基本功能1) 开局:首先选择游戏等级,然后生成不同等级的雷区界面。
游戏等级分为三级:各等级方块数为——初级:9×9、中级:16×16、高级:24×24;自定义:X,各级地雷数分别为10,40,99;雷区每个方块下面或埋藏有1个地雷,或者没有地雷;2) 挖雷:鼠标点击方块,可挖开它;若所揭方块下有雷,则踩雷,此时所有含地雷的块都标记,该局游戏失败;如果方块上出现数字,它代表在它周围的8个方块中共有多少颗地雷;3) 标记地雷:在某个光标上点击鼠标右键,则标记此块下埋着地雷(实际上可能是误标),显示为F。
每标记一个地雷,地雷数减少1;4) 自动挖开:如果某个数字方块周围的地雷全都标记完,则自动将其剩下的方块挖开;5) 扩散:扫雷程序还会自动展开已确定没有雷的雷区。
如果a[3,4]周围雷数为1,a[2,3]已被标示为地雷,那么a[24],a[25],a[33],a[35],a[43],a[44],a[45]将被展开,一直波及到不可确定的雷区。
6) 游戏数据的记录:对于得分较高的玩家进行统计,保存在“mine.log”文件中。
7)用于记录游戏时间的独立线程,并在界面实时显示游戏时间。
7)总体设计开发环境:Windows Xp sp3+NetBeans IDE1.项目包的UML视图:图1-项目包视图项目由三个包组成:●saolei.game.mine 功能:这个包是游戏的核心,其中实现了主界面,核心算法,图片管理,等级记录等功能●saolei.awt 功能:实现LedNumber类,把数字格式化为液晶显示图片●saolei.swing 功能:实现 AboutDialog类,响应about事件。
java习题7答案与解析Java习题7答案与解析Java是一门广泛应用于软件开发领域的编程语言,具有简洁、可移植、高效等特点。
在学习Java的过程中,习题是不可或缺的一部分,通过解答习题可以提高编程能力和理解对Java的掌握程度。
本文将为大家提供一些Java习题7的答案与解析,希望对大家的学习有所帮助。
1. 请编写一个Java程序,实现将一个字符串中的大写字母转换为小写字母,并输出结果。
答案与解析:可以使用String类的toLowerCase()方法将字符串中的大写字母转换为小写字母。
具体代码如下:```javapublic class ConvertToUpper {public static void main(String[] args) {String str = "Hello World";String result = str.toLowerCase();System.out.println(result);}}```2. 请编写一个Java程序,实现计算一个数组中所有元素的和,并输出结果。
答案与解析:可以使用循环遍历数组,将每个元素累加到一个变量中,最后输出结果。
具体代码如下:public class ArraySum {public static void main(String[] args) {int[] arr = {1, 2, 3, 4, 5};int sum = 0;for (int i = 0; i < arr.length; i++) {sum += arr[i];}System.out.println("数组元素的和为:" + sum);}}```3. 请编写一个Java程序,实现将一个字符串按照指定分隔符分割,并输出结果。
答案与解析:可以使用String类的split()方法将字符串按照指定分隔符进行分割,并将结果存储在一个字符串数组中。
java基础试题及答案初中1. Java是一种______语言。
A. 编译型B. 解释型C. 编译与解释混合型D. 标记型答案:C2. Java程序的执行流程是______。
A. 源代码→ 编译器→ 字节码→ JVM → 操作系统B. 源代码→ 解释器→ 字节码→ JVM → 操作系统C. 源代码→ 编译器→ 字节码→ JVM → 本地机器指令D. 源代码→ 解释器→ 字节码→ 本地机器指令答案:C3. 在Java中,下列哪个关键字用于声明一个类?A. classB. interfaceC. structD. enum答案:A4. Java中,下列哪个数据类型是基本数据类型?A. StringB. intC. ArrayListD. HashMap答案:B5. 在Java中,下列哪个关键字用于实现继承?A. extendsB. implementsC. overrideD. abstract答案:A6. Java中,下列哪个关键字用于声明一个接口?A. classB. interfaceC. abstractD. final答案:B7. 在Java中,下列哪个关键字用于声明一个方法?A. methodB. functionC. voidD. def答案:C8. 在Java中,下列哪个关键字用于声明一个变量?A. varB. letC. constD. final答案:A9. 在Java中,下列哪个关键字用于声明一个常量?A. constB. finalC. staticD. volatile答案:B10. 在Java中,下列哪个关键字用于实现多态?A. abstractB. interfaceC. overrideD. implements答案:C11. 在Java中,下列哪个关键字用于声明一个静态方法?A. staticB. finalC. abstractD. volatile答案:A12. 在Java中,下列哪个关键字用于声明一个同步方法?A. synchronizedB. volatileC. finalD. transient答案:A13. 在Java中,下列哪个关键字用于声明一个线程安全的类?A. synchronizedB. volatileC. finalD. thread-safe答案:D14. 在Java中,下列哪个关键字用于声明一个单例类?A. singletonB. uniqueC. finalD. static答案:A15. 在Java中,下列哪个关键字用于声明一个泛型?A. genericB. typeC. classD. extends答案:B16. 在Java中,下列哪个关键字用于声明一个异常?A. exceptionB. errorC. throwableD. try答案:C17. 在Java中,下列哪个关键字用于声明一个枚举?A. enumB. listC. setD. map答案:A18. 在Java中,下列哪个关键字用于声明一个注解?A. annotationB. @interfaceC. commentD. note答案:B19. 在Java中,下列哪个关键字用于声明一个内部类?A. innerB. nestedC. staticD. private答案:B20. 在Java中,下列哪个关键字用于声明一个匿名内部类?A. anonymousB. unnamedC. newD. this答案:C。
java编程练习题及答案Java编程练习题及答案一、选择题1. 在Java中,哪个关键字用于定义类?A. classB. interfaceC. enumD. struct答案:A2. 下列哪个是Java中的合法标识符?A. 2variableB. forC. variable2D. class答案:C3. 在Java中,哪个方法用于获取当前对象的引用?A. this()B. super()C. clone()D. new()答案:A4. 以下哪个是Java的访问修饰符?A. publicB. staticC. finalD. abstract答案:A5. 在Java中,哪个关键字用于定义接口?A. classB. interfaceC. abstractD. enum答案:B二、简答题1. 请简述Java中的继承是如何工作的?答案:Java中的继承允许一个类(子类)继承另一个类(父类)的属性和方法。
子类可以扩展或修改父类的行为,实现代码复用。
继承是面向对象编程的核心概念之一。
2. 请解释Java中接口和抽象类的区别?答案:接口定义了一组方法规范,但不提供实现。
任何实现接口的类都必须提供接口中所有方法的具体实现。
抽象类可以包含抽象方法和具体方法,并且可以有成员变量。
抽象类可以作为其他类的基类,但不能被实例化。
三、编程题1. 编写一个Java程序,实现一个简单的计算器,可以进行加、减、乘、除运算。
```javaimport java.util.Scanner;public class SimpleCalculator {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入第一个数字: ");double num1 = scanner.nextDouble();System.out.print("请选择运算符(+, -, *, /): "); char operator = scanner.next().charAt(0);System.out.print("请输入第二个数字: ");double num2 = scanner.nextDouble();double result = 0;switch (operator) {case '+':result = num1 + num2;break;case '-':result = num1 - num2;break;case '*':result = num1 * num2;break;case '/':if (num2 != 0) {result = num1 / num2;} else {System.out.println("除数不能为0"); }break;default:System.out.println("无效的运算符");}if (result != 0) {System.out.println("结果是: " + result);}scanner.close();}}```2. 编写一个Java程序,实现一个简单的学生管理系统,可以添加学生信息、显示所有学生信息。
第七章Java图形用户界面1、阅读下面的程序,回答问题。
import java.awt.*;import javax.swing.*;public class T extends JFrame {public T ( ) {super("GridLayout");Container con=this.getContentPane();con.setLayout(new GridLayout(2,3));con.add(new JButton("a"));con.add(new JButton("b"));con.add(new JButton("c"));con.add(new JButton("d"));con.add(new JButton("e"));con.add(new JButton("f"));setSize(200, 80);setVisible(true);}public static void main(String args[]) {new T();}}◆画图表示程序运行后的图形界面。
如果程序通过实现某个接口处理按钮的动作事件,则该接口名为何?接口中的方法头声明如何?实现的接口是ActionListener该接口的方法声明是public void actionPerformed(ActionEvent e)2、编写一个简单的计算器,要求图形用户界面如下图所示。
import java.awt.*;import java.awt.event.*;import javax.swing.*;public class TestZ extends JFrame implements ActionListener{private JPanel jPanel1,jPanel2;private JTextField resultField;private JButton s1,s2,s3,s4,s5,s6,s7,s8,s9,s0,b1,b2,b3,b4,b5,b6,b7,b8,f1,f2;private boolean end,add,sub,mul,div;private String str;private double num1,num2;public TestZ(){super("计算器");setSize(300,240);Container con=getContentPane();con.setLayout(new BorderLayout());jPanel1=new JPanel();jPanel1.setLayout(new GridLayout(1,1));jPanel2=new JPanel();jPanel2.setLayout(new GridLayout(4,4)); resultField=new JTextField("0"); jPanel1.add(resultField);con.add(jPanel1,BorderLayout.NORTH); s1=new JButton(" 1 ");s1.addActionListener(this);s2=new JButton(" 2 ");s2.addActionListener(this);s3=new JButton(" 3 ");s3.addActionListener(this);s4=new JButton(" 4 ");s4.addActionListener(this);s5=new JButton(" 5 ");s5.addActionListener(this);s6=new JButton(" 6 ");s6.addActionListener(this);s7=new JButton(" 7 ");s7.addActionListener(this);s8=new JButton(" 8 ");s8.addActionListener(this);s9=new JButton(" 9 ");s9.addActionListener(this);s0=new JButton(" 0 ");s0.addActionListener(this);b1=new JButton(" + ");b1.addActionListener(this);b2=new JButton(" - ");b2.addActionListener(this);b3=new JButton(" * ");b3.addActionListener(this);b4=new JButton(" / ");b4.addActionListener(this);f1=new JButton(" . ");f1.addActionListener(this);f2=new JButton(" = ");f2.addActionListener(this);jPanel2.add(s1);jPanel2.add(s2);jPanel2.add(s3);jPanel2.add(b1);jPanel2.add(s4);jPanel2.add(s5);jPanel2.add(s6);jPanel2.add(b2);jPanel2.add(s7);jPanel2.add(s8);jPanel2.add(s9);jPanel2.add(b3);jPanel2.add(s0);jPanel2.add(f1);jPanel2.add(f2);jPanel2.add(b4);con.add(jPanel2,BorderLayout.CENTER); }public void num(int i){String s = null;s=String.valueOf(i);if(end){ //如果数字输入结束,则将文本框置零,重新输入resultField.setText("0");end=false;}if((resultField.getText()).equals("0")){ //如果文本框的内容为零,则覆盖文本框的内容resultField.setText(s);}else{ //如果文本框的内容不为零,则在内容后面添加数字str = resultField.getText() + s;resultField.setText(str);}}public void actionPerformed(ActionEvent e){ //数字事件if(e.getSource()==s1)num(1);else if(e.getSource()==s2)num(2);else if(e.getSource()==s3)num(3);else if(e.getSource()==s4)num(4);else if(e.getSource()==s5)num(5);else if(e.getSource()==s6)num(6);else if(e.getSource()==s7)num(7);else if(e.getSource()==s8)num(8);else if(e.getSource()==s9)num(9);else if(e.getSource()==s0)num(0);//符号事件else if(e.getSource()==b1)sign(1);else if(e.getSource()==b2)sign(2);else if(e.getSource()==b3)sign(3);else if(e.getSource()==b4)sign(4); //等号else if(e.getSource()==f1){str=resultField.getText();if(str.indexOf(".")<=1){str+=".";resultField.setText(str);}}else if(e.getSource()==f2){num2=Double.parseDouble(resultField.getText());if(add){num1=num1 + num2;}else if(sub){num1=num1 - num2;}else if(mul){num1=num1 * num2;}else if(div){num1=num1 / num2;}resultField.setText(String.valueOf(num1));end=true;}}public void sign(int s){if(s==1){add=true;sub=false;mul=false;div=false;}else if(s==2){add=false;sub=true;mul=false;div=false;}else if(s==3){add=false;sub=false;mul=true;div=false;}else if(s==4){add=false;sub=false;mul=false;div=true;}num1=Double.parseDouble(resultField.getText());end=true;}public static void main(String[] args){TestZ th1=new TestZ();th1.show();}}3、请编写一个简单的用户登录程序。
要求使用图形用户界面,用户名和密码假定均为java,且密码输入时全部显示为星号(*)。
import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.*;public class JavaApplication49 {public static void main(String[] args) {MyLand my=new MyLand();}}class MyLand {int a=0;public MyLand(){JFrame frame = new JFrame();frame.setBounds(450,300,370,220);Font font=new Font("宋体",Font.PLAIN,30);frame.setFont(font);frame.setLayout(new BorderLayout());JPanel paneltop = new JPanel();paneltop.add(new JLabel("用户登陆",JLabel.CENTER));frame.add(paneltop,BorderLayout.NORTH);frame.setVisible(true);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JPanel panel_1 = new JPanel(new GridLayout(3,1));frame.add(panel_1,BorderLayout.CENTER);JPanel panel_11 = new JPanel(new FlowLayout());JPanel panel_12 = new JPanel(new FlowLayout());JPanel panel_13 = new JPanel(new GridLayout(1,5));panel_1.add(panel_11);panel_1.add(panel_12);panel_1.add(panel_13);panel_11.add(new JLabel("用户名:"));final JTextField text1 = new JTextField("",10);panel_11.add(text1);panel_12.add(new JLabel("用户密码:"));final JPasswordField text2 = new JPasswordField("",10);text2.setEchoChar('*');panel_12.add(text2);JButton b=new JButton("确定");class MyExam7_3 implements ActionListener{public void actionPerformed(ActionEvent e){JDialog dialog=new JDialog();dialog.setBounds(450, 200,560,400);dialog.setVisible(true);Font font1 = new Font("宋体",Font.BOLD,70);dialog.setFont(font1);if((text1.getText()).equalsIgnoreCase("java")&&String.valueOf(text2.getPassword()).equals("java")){dialog.add(new JLabel("登陆成功!",JLabel.CENTER));}elsedialog.add(new JLabel("密码或用户名错误!",JLabel.CENTER));}}b.addActionListener(new MyExam7_3());panel_13.add(new Label(" "));panel_13.add(new Label(" "));panel_13.add(b);panel_13.add(new Label(" "));panel_13.add(new Label(" "));}}4、编写一个显示六个标签的框架,将标签前景色设为黑色、蓝色、青色、绿色、红色、橙色,标签边界为黄色边界,标签字体为TimesRoman、加粗、20像素,每个标签的文本为前景色名字。