Java黑皮书课后题第8章:**8.14(探讨矩阵)编写程序,提示用户输入一个方阵的长度,随机地在矩阵中填入0和1,打印这个矩阵,然后找出整行、整列或者对角线都是1或0的行、列和对角线
生活随笔
收集整理的這篇文章主要介紹了
Java黑皮书课后题第8章:**8.14(探讨矩阵)编写程序,提示用户输入一个方阵的长度,随机地在矩阵中填入0和1,打印这个矩阵,然后找出整行、整列或者对角线都是1或0的行、列和对角线
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
**8.14(探討矩陣)編寫程序,提示用戶輸入一個方陣的長度,隨機(jī)地在矩陣中填入0和1,打印這個矩陣,然后找出整行、整列或者對角線都是1或0的行、列和對角線
- 題目
- 題目描述與運行示例
- 破題
- 代碼
題目
題目描述與運行示例
**8.14(探討矩陣)編寫程序,提示用戶輸入一個方陣的長度,隨機(jī)地在矩陣中填入0和1,打印這個矩陣,然后找出整行、整列或者對角線都是1或0的行、列和對角線
運行示例:
破題
代碼
import java.util.Scanner;public class Test8_14 {public static void main(String[] args) {//1. 從控制臺獲取matrix大小(輸出提示語句)Scanner input = new Scanner(System.in);System.out.print("Enter the size for the matrix: ");int length = input.nextInt();//2. 聲明一個二維數(shù)組,長度為剛剛輸入的大小int[][] arr = new int[length][length];//3. 遍歷數(shù)組給數(shù)組賦值(int)(Math.random()*2),同時輸出元素,每行結(jié)尾換行for (int i = 0 ; i < length ; i++){for (int j = 0 ; j < length ; j++){arr[i][j] = (int)(Math.random()*2);System.out.print(arr[i][j]);}System.out.println();}//4. 找整行為0、1的行下標(biāo),分情況輸出int temp1 = 0;boolean bool1 = true, have_output = false;for (int i = 0 ; i < length ; i++){temp1 = arr[i][0];bool1 = true;for (int j = 0 ; j < length ; j++){if (arr[i][0] != arr[i][j]){bool1 = false;}}if (bool1){System.out.println("All " + temp1 + "s on row " + i);have_output = true;}}if ( ! have_output ){System.out.println("No same numbers on a row");}//5. 找整列為0、1的列下標(biāo),分情況輸出int temp2 = 0;boolean bool2 = true;have_output = false;for (int j = 0 ; j < length ; j++){temp2 = arr[j][0];bool2 = true;for (int i = 0 ; i < length ; i++){if (arr[j][0] != arr[i][j]){bool2 = false;}}if (bool2){System.out.println("All " + temp2 + "s on col " + j);have_output = true;}}if ( ! have_output ){System.out.println("No same numbers on a column");}//6. 判斷主對角線是否全部為0、1,分情況輸出int temp3 = arr[0][0];boolean bool3 = true;for (int i = 0 ; i < length ; i++){if (temp3 != arr[i][i])bool3 = false;}if (bool3){System.out.println("All " + temp3 + "s on the major diagonal");} else {System.out.println("No same numbers on the major diagonal");}//7. 判斷副對角線是否全部為0、1,分情況輸出int temp4 = arr[0][length-1];boolean bool4 = true;for (int i = 0 ; i < length ; i++){if (temp3 != arr[i][length - i - 1])bool4 = false;}if (bool4){System.out.println("All " + temp4 + "s on the sub-diagonal");} else {System.out.println("No same numbers on the sub-diagonal");}} }總結(jié)
以上是生活随笔為你收集整理的Java黑皮书课后题第8章:**8.14(探讨矩阵)编写程序,提示用户输入一个方阵的长度,随机地在矩阵中填入0和1,打印这个矩阵,然后找出整行、整列或者对角线都是1或0的行、列和对角线的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java黑皮书课后题第8章:*8.13(
- 下一篇: Java黑皮书课后题第8章:*8.15(