我正在研究一個項目,我必須讀取一個文件並將內容輸入到二維數組中。然後我必須對矩陣的每一行,每一列和周長進行求和。除了外圍,我擁有的一切工作至今。我正嘗試爲兩個外側列的頂行,底行和中間創建單獨的for循環。找到二維數組的總和java
矩陣文件看起來像這樣:
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);
}
}
我會hugeeeeeely感激,如果有人可以幫助我在第一列和最後一列的中間(應該是2 + 2和8 + 8)。或者如果你有一個更好的方式找到周邊。提前致謝!
你讓一切都太複雜了。您不需要兩個for循環來計算一個行/列。實際上,每次for循環只執行一次迭代。因此,如果您知道for循環只執行一次迭代,請修正該值並且不要用於循環 – Martinsos 2013-03-26 13:49:59