8 Replies Latest reply: Apr 19, 2009 7:04 PM by 800308 RSS

    Returning 2D array from method

    843789
      Hi all. I'm working on a lab (simple stuff by all standards, but I'm still quite "green"). We're being introduced to returning 2D arrays/ passing them. I've looked at several similar examples and scoured a book, and for the life of me don't know why this won't compile. The errors are below it. I'm sure my answer is within the error message but I just don't see it. Thanks in advance...
      //Lab 8
      //Input:     Size of arrays, integers for arrays, choice of addition, subtraction, or multiplication.
      //Output:      Matrix result of arithmetic on two arrays.
      //Get the size of two arrays and fill them with integers. Let the user choose addition, subtraction, or
      //multiplication of those arrays and display it in a matrix format.
      
      import java.text.*; //for DecimalFormat class
      import java.util.*; //for Scanner class
      
      public class Lab82DArraysKevinRice2
      {
           public static void main(String[] args)
           {
                //Variable declarations
                int arrayLength = 0;
                int arithmeticChoice = 0;
                                    
                Scanner keyboard= new Scanner(System.in);
                
                //Begin main method with an introduction and request the size of the arrays.
                //Enter -1 to quit.
                System.out.println("Welcome to array arithmetic.");
                System.out.println("Enter the number of rows and columns for the arrays.");
                System.out.println("Just one number since #rows = #columns. Enter -1 to exit.");
      
                arrayLength = keyboard.nextInt();
                                         
                if(arrayLength > 0) 
                {
                     //Initialize each of 3 arrays and call the method to load them.
                     int [] [] firstArray = new int [arrayLength] [arrayLength];
                     loadArray (firstArray);
                     
                     int [] [] secondArray = new int [arrayLength] [arrayLength];
                     loadArray (secondArray);
                     
                     int [] [] totalsArray = new int [arrayLength] [arrayLength];
           
                     System.out.println("Would you like to add, subtract, or multiply the arrays?");
                     System.out.println("Enter 1 to add, or 2 to subtract (array1 from array2).");
                     arithmeticChoice = keyboard.nextInt();
      
                     switch(arithmeticChoice)
                     {
                          case 1:
                               totalsArray = addArrays(firstArray, secondArray);
                               outputArray(firstArray);
                               System.out.println("+");
                               outputArray(secondArray);
                               System.out.println("=");
                               outputArray(totalsArray);
                               break;
                          case 2:
                               subtractArrays(firstArray, secondArray);
                               break;                         
                     }
                     
                }
                System.out.println("Array arithmetic will end now.");
           }
                
           public static void loadArray (int [] [] arrayName)
           //Loads an array of integers. Array is passed.
           {          
                Scanner keyboard= new Scanner(System.in);
                System.out.println("Enter " + (arrayName.length * arrayName.length) + " integers.");
                
                //Outer, or row loop.
                for(int i = 0; i < arrayName.length; i ++) 
                {
                     //Inner loop to fill columns across each row.
                     for(int j = 0; j < arrayName.length; j ++)
                     {
                          arrayName  [j]= keyboard.nextInt();
                     }
                }               
           }
           
           public static int addArrays (int [][] array1, int [][] array2)
           {
                int [] [] equalsArray = new int [array1.length] [array1.length];
                
                for(int i = 0; i < array1.length; i ++)
                {
                     for(int j = 0; j < array1.length; j ++)
                     {
                          equalsArray [i] [j]= array2 [i] [j] - array1 [i] [j];
                     }
                }     
                return equalsArray;
           }
           
           public static int subtractArrays (int [][] array1, int [][] array2)
           {
                int [] [] equalsArray = new int [array1.length] [array1.length];
                
                for(int i = 0; i < array1.length; i ++)
                {
                     //Inner loop to fill columns across each row.
                     for(int j = 0; j < array1.length; j ++)
                     {
                          equalsArray [i] [j]= array1 [i] [j] - array2 [i] [j];
                     }
                }     
           }
           
           public static void outputArray (int [][] a)
           {
                for(int i = 0; i < a.length; i ++)
                {
                     //Inner loop to fill columns across each row.
                     for(int j = 0; j < a.length; j ++)
                     {
                          System.out.println(a [i] [j]);
                          System.out.print(" ");
                     }
                }     
           }
           
      }
      The errors:
      ----jGRASP exec: javac -g F:\COS102\8\Lab82DArraysKevinRice2.java

      Lab82DArraysKevinRice2.java:47: incompatible types
      found : int
      required: int[][]
                               totalsArray = addArrays(firstArray, secondArray);
                               ^
      Lab82DArraysKevinRice2.java:91: incompatible types
      found : int[][]
      required: int
                return equalsArray;
                ^
      2 errors

      ----jGRASP wedge2: exit code for process is 1.
      ----jGRASP: operation complete.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
        • 1. Re: Returning 2D array from method
          843789
          Also, I know that I have different structure in the methods. When I can get addArrays to run, I'll fix the rest easily... thx
          • 2. Re: Returning 2D array from method
            843789
            The errors go together.
            {noformat}
            found   : int[][]
            required: int
            return equalsArray;
                   ^
            {noformat}
            This one is saying you are returning equalsArray which is a 2D array, but the method was declared to return an int.
            {noformat}
            found   : int
            required: int[][]
            totalsArray = addArrays(firstArray, secondArray);
                                   ^
            {noformat}
            And this one is saying that totalsArray was declared as a 2D array but you are trying to assign an int to it. The compiler is convinced that it's an int you are trying to assign, because you have declared the method to return an int.

            Both errors are, therefore, solved by changing the return type of the method so that it says the method will return a 2D array.
            int[][] foo() {
                // etc
            • 3. Re: Returning 2D array from method
              843789
              I knew I'd cringe when I read how on the nose it would be. Thanks.
              • 4. Re: Returning 2D array from method
                843789
                You're welcome.

                In part the confusion because you have adopted two different ways of going about working with the matrices. For loadArray() you pass a reference to a newly created matrix and work with it "in place": that is the method puts values into the matrix whose reference it was passed. For addArrays() - and subtractArrays() when you get it done - you adopt a different approach and let the method create a new matrix, put stuff into it and then return a reference to that matrix.

                Both approaches are ok - but the mixture might (as you've found) be confusing. There's no reason why loadArray() couldn't actually return a reference to a (ewly created) matrix like addArrays() does.

                Another point: because addArrays() creates the new matrix you don't have to initialise the variable in the main method where you do. In the following the commented out line at the start creates a new matrix and initialises totalsArray to be a reference to it. But this reference is later thrown away when totalsArray is assigned the reference returned by addArrays().
                //int [] [] totalsArray = new int [arrayLength] [arrayLength];
                int [] [] totalsArray;
                     
                System.out.println("Would you like to add, subtract, or multiply the arrays?");
                System.out.println("Enter 1 to add, or 2 to subtract (array1 from array2).");
                arithmeticChoice = keyboard.nextInt();
                 
                switch(arithmeticChoice)
                {
                    case 1:
                        totalsArray = addArrays(firstArray, secondArray);
                        // etc
                • 5. Re: Returning 2D array from method
                  843789
                  Thanks! Very helpful. I'm trying to picture the reference approach for loadArray. I'll try it. Thanks again, it feels good to be up and running here. :)
                  • 6. Re: Returning 2D array from method
                    843789
                    It wasn't my intention to interrupt your flow of thought - so feel free to press on and put aside the more general comments. If it helps your mental picture change the name of the method from loadArray() to createArray().
                    • 7. Re: Returning 2D array from method
                      843789
                      Not an interruption at all, but appreciated. I guess "create" is wherein the difference lies between the two styles...
                      • 8. Re: Returning 2D array from method
                        800308
                        My 2C...

                        Given a choice, I'd always go for int[] createArray() over loadArray(int[]);.

                        Mutating parameters inside a method is just asking for trouble. "Unexpected mutation" is the third most common source of bugs in C/++ code (if I recall rightly)... especially pointers, p2ps, and extra-specially p2p2ps.