2013-03-26 3 views
2

Je travaille sur un projet où je dois lire un fichier et entrer le contenu dans un tableau 2D. Ensuite, je dois additionner chaque rangée, chaque colonne et le périmètre de la matrice. J'ai tout fonctionné jusqu'ici excepté le périmètre. J'essaie de créer des boucles séparées pour la rangée du haut, la rangée du bas et le milieu des deux colonnes extérieures.trouver la somme de deux dimensions java tableau

Le fichier de matrice ressemble à ceci:

1 2 3 4 
2 4 6 8 
2 4 6 8 
3 2 3 4 

Par conséquent, le périmètre devrait ajouter jusqu'à 42. Je peux En ce moment ajouter avec succès la première ligne et la dernière rangée à l'égalité 22. Cependant, quand j'ajoute les colonnes à ce total je reçois 32.

Voici le code:

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); 
    } 

    } 

Je serais hugeeeeeely reconnaissant si quelqu'un pouvait me aider à tal au milieu de la première et dernière colonne (devrait être 2 + 2 et 8 + 8). Ou si vous avez une meilleure façon de trouver le périmètre. Merci d'avance!

+0

Vous avez fait tout trop compliqué. Vous n'avez pas besoin de deux boucles pour compter une seule ligne/colonne. En fait chaque fois qu'une de vos boucles for ne fait qu'une seule itération.Donc, si vous savez que la boucle va faire une seule itération, corrigez cette valeur et ne l'utilisez pas pour la boucle – Martinsos

Répondre

2

Je recommande que vous le faire de cette façon:

int perTotal = 0; 
// top and bottom row 
for (int c = 0; c < numCols; c++) 
    perTotal += matrix[0][c] + matrix[numRows-1][c]; 
// left and right column 
for (int r = 1; r < numRows-1; r++) 
    perTotal += matrix[r][0] + matrix[r][numCols-1]; 

// output 
System.out.println("Perimeter=" + perTotal); 
+0

Dans le cas où il n'y a qu'une seule ligne, vous le résumez deux fois pour calculer le périmètre ... Je ne sais pas quoi faire dans ce cas, dans ma réponse, j'ai considéré pour le résumer une seule fois avec un si. – LaGrandMere

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

     int perTotal = 0; 

     // First line 
     for (int j = 0; j < numCols; j++) 
     { 
      perTotal += matrix[0][j]; 
     } 

     // If there is only one line, then it is done. 
     if (numRows > 1) 
     { 
      // Last line 
      for (int j = 0; j < numCols; j++) 
      { 
       perTotal += matrix[numRows-1][j]; 
      } 

      // Other lines 
      for (int i = 1; i < numRows -1); i++) 
      { 
       perTotal += matrix[i][0] + matrix[i][numcols -1]; 
      } 
     } 

    //Perimeter 
    System.out.println("Perimter="+perTotal); 
+0

Si vous gérez un cas lorsqu'il n'y a qu'une seule ligne, vous devez également gérer le cas lorsqu'il n'y a qu'une seule colonne – Martinsos

2

Voici votre méthode:

public static int perimeter(int[][] array) { 
    int perimter = 0; 
    for (int i = 0; i < array[0].length; i++) { 
     perimter += array[0][i] + array[array.length - 1][i]; 
    } 
    for (int r = 1; r < array.length - 1; r++) { 
     perimter += array[r][0] + array[r][array[0].length - 1]; 
    } 
    return perimter; 
} 

Et voici votre test avec le tableau que vous avez fourni:

public static void principal (String [] args) { System.out.println (périmètre (new int [] [] {{1, 2, 2, 3}, {2, 4, 4, 2}, {3, 6, 6, 3}, {4, 8 8, 4}})); }

Sortie: 42

0

vous remercie tous beaucoup! une façon plus simple de le faire. FYI: J'ai fini par faire

int perTotal = 0; 
    for (int i = 0; i < numCols; i++) 
    { 
     perTotal += matrix[0][i] + matrix[numRows-1][i]; 
    } 
    for (int j = 1; j < numRows-1; j++) 
    { 
     perTotal += matrix[j][0] + matrix[j][numCols-1]; 
    } 
    System.out.println("Perimeter = " + perTotal); 
2

Il y a une la4j (algèbre linéaire pour Java) bibliothèque qui gère cette tâche 0.4.0 version (actuellement avaliable à GitHub: https://github.com/vkostyukov/la4j, sera avaliable à Maven cet été). Donc, voici l'exemple bref:

Matrix a = new Basic2DMatrix(...); // creates a real matrix 

// calculates the sum of '1' row 
double d1 = a.foldRow(1, Matrices.asSumAccumulator(0)); 
// calculates the sum of '2' 
double d2 = a.foldColumn(2, Matrices.asSumAccumulator(0)); 

// the helper class that fetches border elements of matrix 
class PerimeterFetcher implements MatrixFunction { 

    private int rows; 
    private int columns; 

    public PerimeterFectcher(int rows, int columns) { 
    this.rows = rows; 
    this.columns = columns; 
    }  

    @Override 
    public double evaluate(int i, int j, double value) { 
    return i == 0 ? value : j == 0 ? value : (i + 1) == rows ? value 
      : (j + 1) == columns ? value : 0; 
    } 
} 

// calculates the perimeter of matrix 
double p = a.fold(Matrices.asSumFunctionAccumulator(0, 
        new PerimeterFetcher(a.rows(), a.columns())));  

UPD: La prochaine version de la4j (0.4.5) prend en charge la méthode sum() pour les matrices et vecteurs:

Matrix a = new Basic2DMatrix(...); 
double s = a.sum(); // wrapper around a.fold(...); 
1

Il suffit de le faire:

 for (int i = 0; i < ROWS; i++){ 
      for (int j = 0; j < COLUMNS; j++){ 
      sum = sum + myArray[i][j]; 
     } 
    } 

    System.out.print(sum); 

Cela devrait vous donner la somme.

0

les opérations suivantes:

import java.util.Scanner; 
public class TwoDarray { 

public static void main(String[] args) 
{ 
    Scanner scn=new Scanner(System.in); 

    System.out.print("Enter the first Rows of Array :"); //Input first Rows and Columns 
    int row1 = scn.nextInt(); 
    System.out.print("Enter the first columns of Array:"); 
    int col1 = scn.nextInt(); 
    System.out.print("Enter the second Rows of Array :"); //Input second rows and column 
    int row2 = scn.nextInt(); 
    System.out.print("Enter the second columns of Array:"); 
    int col2 = scn.nextInt(); 

    int arr1[][] = new int[row1][col1];      // Input the elements in first row and column 

      System.out.println("Enter the elements in First row and column"); 
       for(int i=0;i<row1;i++) 
       { 
        for(int j=0;j<col1;j++) 
        { 
         arr1[i][j]=scn.nextInt(); 
        } 
       } 

    int arr2[][] = new int[row2][col2];      // Input the elements in second row and column 

     System.out.println("Enter the elements in second row and column"); 
      for(int i=0;i<row2;i++) 
      { 
       for(int j=0;j<col2;j++) 
       { 
        arr2[i][j]=scn.nextInt(); 
       } 

      } 

    System.out.println("Output of first row and column is ");  //output of first row and column 
     for(int i=0;i<row1;i++) 
     { 
      for(int j=0;j<col1;j++) 
      { 
       System.out.print(arr1[i][j]+" "); 
      } System.out.println(); 
     } 

       System.out.println("output of secound row and column");   //out put of second row and column 
        for(int i=0;i<row2;i++) 
        { 
         for(int j=0;j<col2;j++) 
         { 
          System.out.print(arr2[i][j]+" "); 
         }  System.out.println(); 
        } 


                 //sum of first and second row and column 

        int sum[][] = new int[row1][col1]; 
         for(int i=0;i<row1;i++) 
         { 
          for(int j=0;j<col1;j++) 
          { 
           sum[i][j]=arr1[i][j]+arr2[i][j]; 
          } 
         } 

         System.out.println("sum of two matrix output");   //sum of two matrix output 
          for(int i=0;i<row1;i++) 
          { 
           for(int j=0;j<col1;j++) 
           { 
            System.out.print(sum[i][j]+" "); 
           }  System.out.println(); 
          } 

} 


} 
Questions connexes