0

I'm currently studying and came across a question which asks to find the minimum value within each row of a 2-dimensional array..and then put all of the minimum values within an array. I already wrote some code but the method produces a really strange output at the console rather than the correct result.

I tested it on this 2d array int[][]array={{3,1,8}, {10,12,2}, {5,7,4}}; , and the output I should have gotten is [1,2,4] but instead i get [I@7852e922

Can someone please tell me what I am doing wrong?

Here is the code..

  public static int [] min_row(int[][] n){

  int [] result = new int[n.length];
  int min=0;


  for(int i=0;i<n.length;i++){


       for(int j=0;j<n[0].length;j++){

           if(n[i][j]<n[i][min]){
               min=j;
           }
           result[i]=n[i][min];
       } 


  }

  return result;
  }
Hassan Ali
  • 149
  • 1
  • 4
  • 11
  • That's because you're printing a primitive array instead of its content. To get yoru result you need to iterate over it and print each element inside. – vivianig Aug 24 '15 at 20:58
  • You need to use `System.out.println(Arrays.toString(result))` to display 1D or 2D array results. – ha9u63a7 Aug 24 '15 at 21:03

2 Answers2

1

I suspect you are printing out the array object itself (note that it is preferred on here to provide your entire code, as the other bit of your code is relevant to this problem. I had to guess) i.e.

int[] result = min_row(someArray);
System.out.println(result);

You can't do that, you need to use a loop to print out each element, e.g.:

for(int i=0; i<result.length;i++)
   System.out.println(result[i]);
John C
  • 500
  • 3
  • 8
  • Oh my god...such a silly mistake.. turns out I had the right code..just didn't print output correctly :L Thanks a lot! – Hassan Ali Aug 24 '15 at 21:04
0

 public static int [] min_row(int[][] n){

  int [] result = new int[n.length];


  for(int i=0;i<n.length;i++){
       int min = Integer.MAX_VALUE;  //initial min with MAX int value
       for(int j=0;j<n[i].length;j++){

           if(min > n[i][j])    // if element smaller than min  
           {
               min= n[i][j];    //assign a new min value
           }
          
       } 
       result[i]= min;          //save the min for the row

  }

  return result;
  }
Peter Peng
  • 1,910
  • 1
  • 27
  • 37