Java黑皮书课后题第8章:**8.36(拉丁方阵)拉丁方阵是一个n*n的数组,其中有n个不同的拉丁字母,并且每个拉丁字母恰好只在每行和每列中出现一次。编写一个程序,提示用户输入数字n和字符数组
生活随笔
收集整理的這篇文章主要介紹了
Java黑皮书课后题第8章:**8.36(拉丁方阵)拉丁方阵是一个n*n的数组,其中有n个不同的拉丁字母,并且每个拉丁字母恰好只在每行和每列中出现一次。编写一个程序,提示用户输入数字n和字符数组
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
**8.36(拉丁方陣)拉丁方陣是一個n*n的數組,其中有n個不同的拉丁字母,并且每個拉丁字母恰好只在每行和每列中出現一次
- 題目
- 題目描述與運行示例
- 破題
- 代碼
題目
題目描述與運行示例
**8.36(拉丁方陣)拉丁方陣是一個n*n的數組,其中有n個不同的拉丁字母,并且每個拉丁字母恰好只在每行和每列中出現一次。
編寫一個程序,提示用戶輸入數字n和字符數組,如示例輸出所示,檢測該輸出數組是否是一個拉丁方陣。字符是從A開始的前面n個字符
破題
代碼
import java.util.Arrays; import java.util.Scanner;public class Test8_36 {public static void main(String[] args) {//1. 輸出提示長度輸入語句并從控制臺獲取,賦值給int對象nScanner input = new Scanner(System.in);System.out.print("Enter a number n: ");int n = input.nextInt();//2. 聲明二維數組,長度為n*nint[][] arr = new int[n][n];//3. 新建一個int型對象,賦值為65+n(規定輸入范圍)int limit_max = 65 + n;//4. 輸出提示語句,新建一個String型對象用于臨時保存System.out.println("Enter "+ n + " rows of letters separated by spaces: ");char temp_str;int temp_int = 0;//5. 遍歷空二維數組,將輸入數據轉為int型判斷是否合法再賦值for (int i = 0 ; i < n ; i++){for (int j = 0 ; j < n ; j++){temp_str = input.next().charAt(0);temp_int = (int) temp_str;if (temp_int >= 65 && temp_int < limit_max){arr[i][j] = temp_int;} else {System.out.println("Wrong input: the letters must be from A to " + (char)(limit_max - 1));return;}}}//6. 兩次遍歷二維數組,元素作為一維數組下標,判斷是否重復+7. 根據結果輸出int[] count = new int[65 + n];for (int i = 0 ; i < n ; i++){Arrays.fill(count, 0);for (int j = 0 ; j < n ; j++){if (count[arr[i][j]] == 0){++count[arr[i][j]];} else {System.out.println("The input array is not Latin square");return;}}}for (int j = 0 ; j < n ; j++){Arrays.fill(count, 0);for (int i = 0 ; i < n ; i++){if (count[arr[i][j]] == 0){++count[arr[i][j]];} else {System.out.println("The input array is not Latin square");return;}}}System.out.println("The input array is Latin square");} }總結
以上是生活随笔為你收集整理的Java黑皮书课后题第8章:**8.36(拉丁方阵)拉丁方阵是一个n*n的数组,其中有n个不同的拉丁字母,并且每个拉丁字母恰好只在每行和每列中出现一次。编写一个程序,提示用户输入数字n和字符数组的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java黑皮书课后题第8章:***8.3
- 下一篇: Java黑皮书课后题第8章:**8.37