私は、ファイルを読み取ってコンテンツを2D配列に入力する必要があるプロジェクトに取り組んでいます。次に、各行、各列、およびマトリックスの周囲長を合計する必要があります。これまでのところ、境界を除いてすべてが機能しています。一番上の行、一番下の行、および2つの外側の列の中央に別々の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でなければなりません)。または、境界を見つけるための完全に優れた方法がある場合。前もって感謝します!