dimanche 28 juin 2015

How to sum two dimensional arrays in Java?

I've created a short code to practice two-dimensional arrays but I've stumbled upon a problem that I can't solve in my code. Hope you guys can help me.

Desired Output:

Enter number:1
Enter number:2
Enter number:3

NUMBERS THAT YOU ENTERED:
1
2
3

TOTAL: 6

Enter number:1
Enter number:2
Enter number:3

NUMBERS THAT YOU ENTERED:
1
2
3

TOTAL: 6

But instead I'm seeing this:

Enter number:1
Enter number:2
Enter number:3

NUMBERS THAT YOU ENTERED:
1
2
3

TOTAL: 6

Enter number:1
Enter number:2
Enter number:3

NUMBERS THAT YOU ENTERED:
1
2
3

TOTAL: 12

______________________________________________________

It's adding up every number that I input instead of just adding three numbers in each iteration. Please check the code below:

PART I

package Test;

 public class Test1 {
   private int[][] number;
   private int number1;
   public Test1(int[][]n){
      number = new int[2][3];
    for(int dx = 0;dx < number.length;dx++){
        for(int ix = 0;ix < number[dx].length;ix++){
            number[dx][ix]=n[dx][ix];
        }

    }
}

public Test1(int n){
    number1 = n;
}

public int getTotal(){
    int total = 0;

    for(int dx = 0;dx < number.length;dx++){
        for(int ix = 0;ix < number[dx].length;ix++){
            total += number[dx][ix];
        }

    }

    return total;
}

public int getNumbers(){

    return number1;
}

}

PART II

  package Test;
  import java.util.Scanner;
  public class TestMain {
  public static void main(String[]args){
    final int DIVS = 2;
    final int NUM_INSIDE = 3;
    Test1[][] t1 = new Test1[DIVS][NUM_INSIDE];
    int[][]numbers = new int[DIVS][NUM_INSIDE];
    getValues(numbers,DIVS,NUM_INSIDE,t1);

}

public static void getValues(int[][]numbers,int DIVS,int NUM_INSIDE,Test1[][] t1){
    Scanner hold = new Scanner(System.in);
    int num;
    for(int div = 0;div < DIVS;div++){
        for(int ins = 0;ins < NUM_INSIDE;ins++){
            System.out.print("Enter number:");
            numbers[div][ins]=hold.nextInt();
            num = numbers[div][ins];
            t1[div][ins] = new Test1(num);

        }
        Test1 t = new Test1(numbers);
        display(t,t1,div);

    }
}

public static void display(Test1 t,Test1[][] t1,int div){
    System.out.print("****************************\n");
    System.out.print("NUMBERS THAT YOU ENTERED:\n");

    for(int y = 0; y < t1[div].length;y++){
        System.out.print(t1[div][y].getNumbers() + "\n");
    }

    System.out.print("****************************\n");
    System.out.print("TOTAL: " + t.getTotal() + "\n");
    System.out.print("****************************\n");
}
}

Aucun commentaire:

Enregistrer un commentaire