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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

二维数组的查找 java_查找二维数组java的总和

發布時間:2023/12/9 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 二维数组的查找 java_查找二维数组java的总和 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我正在一個項目中,我必須讀取文件并將內容輸入2D數組。然后,我必須對每一行,每一列和矩陣的周長求和。到目前為止,除外圍功能外,我一切正常。我正在嘗試為兩個外部列的頂行,底行和中間創建單獨的for循環。

矩陣文件如下所示:

1 2 3 4

2 4 6 8

2 4 6 8

3 2 3 4

因此,周長總計應為42。現在,我可以成功地將第一行和最后一行添加為等于22。但是,當我將列添加到總數中時,我得到32。

這是代碼:

import java.util.*; // Scanner class

import java.io.*; // File class

public class Lab10

{

static public void main( String [ ] args ) throws Exception

{

if ( args.length != 1 )

{

System.out.println("Error -- usage is: java Lab10 matdataN.txt");

System.exit( 0 );

}

//Requirement #1: first int value: # of rows, second int value: # of cols

File newFile = new File(args[0]);

Scanner in = new Scanner(newFile);

int numRows = in.nextInt();

int numCols = in.nextInt();

//Requirement #2: declare two-d array of ints

int[][] matrix;

matrix = new int[numRows][numCols];

//Requirement #3 & 4: read file one line at a time (nested for loops

//and nextInt()) and print

for (int i = 0; i < numRows; i++)

{

for (int j = 0; j < numCols; j++)

{

matrix[i][j] = in.nextInt();

System.out.print(matrix[i][j]+ " ");

}

System.out.println();

}

//Requirement #5: traverse each row and sum the values and display the sums

int rowTotal = 0;

for (int i = 0; i < numRows; i++)

{

rowTotal = 0;

for (int j = 0; j < numCols; j++)

{

rowTotal += matrix[i][j];

}

System.out.println("Sum for row = " + rowTotal);

}

//Requirement #6: traverse each column and sum the values and display the sums

int colTotal = 0;

for (int i = 0; i < numRows; i++)

{

colTotal = 0;

for (int j = 0; j < numCols; j++)

{

colTotal += matrix[j][i];

}

System.out.println("Sum for col = " + colTotal);

}

//Requirement #7: traverse the perimeter and sum the values and display the sum

//sum bottom row matrix

int perTotal = 0;

for (int i = (numRows-1); i < numRows; i++)

{

perTotal = 0;

for (int j = 0; j < numCols; j++)

{

perTotal += matrix[i][j];

}

}

//sum + top row matrix

for (int i = 0; i < numRows - (numRows-1); i++)

{

for (int j = 0; j < numCols; j++)

{

perTotal += matrix[i][j];

}

System.out.println("Sum of perimeter = " + perTotal);

}

// sum + first col middle

for (int i = 1; i < (numRows-1); i++)

{

for (int j = 0; j < numCols - (numCols-1); j++)

{

perTotal += matrix[j][i];

}

System.out.println("Sum = " + perTotal);

}

// sum + last col middle

for (int i = 1; i < (numRows-1); i++)

{

for (int j = (numCols-1); j < numCols; j++)

{

perTotal += matrix[j][i];

}

System.out.println(perTotal);

}

}

如果有人可以幫助我將第一列和最后一列的總和設為2 + 2和8 + 8,我將非常感激?;蛘?#xff0c;如果您有一種更好的方法來尋找周長。提前致謝!

總結

以上是生活随笔為你收集整理的二维数组的查找 java_查找二维数组java的总和的全部內容,希望文章能夠幫你解決所遇到的問題。

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