日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java黑皮书课后题第8章:**8.14(探讨矩阵)编写程序,提示用户输入一个方阵的长度,随机地在矩阵中填入0和1,打印这个矩阵,然后找出整行、整列或者对角线都是1或0的行、列和对角线

發布時間:2024/7/23 java 36 豆豆

**8.14(探討矩陣)編寫程序,提示用戶輸入一個方陣的長度,隨機地在矩陣中填入0和1,打印這個矩陣,然后找出整行、整列或者對角線都是1或0的行、列和對角線

  • 題目
    • 題目描述與運行示例
    • 破題
  • 代碼

題目

題目描述與運行示例

**8.14(探討矩陣)編寫程序,提示用戶輸入一個方陣的長度,隨機地在矩陣中填入0和1,打印這個矩陣,然后找出整行、整列或者對角線都是1或0的行、列和對角線
運行示例:

Enter the size for the matrix: 4 1100 0101 1011 1101 No same numbers on a row No same numbers on a column All 1s on the major diagonal No same numbers on the sub-diagonal

破題

  • 從控制臺獲取matrix大小(輸出提示語句)
  • 聲明一個二維數組,長度為剛剛輸入的大小
  • 遍歷數組給數組賦值(int)(Math.random()*2),同時輸出元素,每行結尾換行(最后一行除外)
  • 找整行為0、1的行下標,分情況輸出
  • 找整列為0、1的列下標,分情況輸出
  • 判斷主對角線是否全部為0、1,分情況輸出
  • 判斷副對角線是否全部為0、1,分情況輸出
  • 代碼

    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. 聲明一個二維數組,長度為剛剛輸入的大小int[][] arr = new int[length][length];//3. 遍歷數組給數組賦值(int)(Math.random()*2),同時輸出元素,每行結尾換行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的行下標,分情況輸出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的列下標,分情況輸出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");}} }

    總結

    以上是生活随笔為你收集整理的Java黑皮书课后题第8章:**8.14(探讨矩阵)编写程序,提示用户输入一个方阵的长度,随机地在矩阵中填入0和1,打印这个矩阵,然后找出整行、整列或者对角线都是1或0的行、列和对角线的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。