Results 1 to 2 of 2
  1. #1
    Desmond is offline Member
    Join Date
    Mar 2010
    Posts
    17
    Rep Power
    0

    Default Problems with array

    Hi

    Please help me with the code below, it is supposed to print the largest array element amongst all the elements initialized. It is not doing that instead, it displays the largest element in the last row. I can't figure out what is wrong

    Java Code:
    import java.io.* ;
    class ArrayMaximum
    {
    public static void main ( String[] args ) throws IOException
      {
        int data2[][] = new int[][] {{3, 90, 5, 8, 1},
                       {1, 4, 4, 129, 13, 12, 58, 77, 12},
                       {9, 1, 13},
                       {0, 2,0,50, 75, 77, 3, -1 }};
    int sum =0;
     int max = data2[0][0];
        for ( int row=0; row < data2.length; row++)
        {
          for ( int col=0; col < data2[row].length-1; col++)
          {
    	  if (data2[row][col+1]>data2[row][col])
    	  	max = data2[row][col+1];
          }
        }
        System.out.println(  max);
      }
    }

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,513
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Desmond View Post
    Java Code:
    	  if (data2[row][col+1]>data2[row][col])
    	  	max = data2[row][col+1];
    That test isn't correct; it tests whether or not a number in a next column is larger than the number in the current column; that's not the way to find a maximum value. You should test the number in the current row/column against the maximum so far.

    kind regards,

    Jos

Similar Threads

  1. Array problems
    By braddy in forum New To Java
    Replies: 4
    Last Post: 10-09-2010, 01:18 PM
  2. Two simple array problems.
    By DMiller in forum New To Java
    Replies: 4
    Last Post: 11-06-2009, 11:50 AM
  3. Array problems!
    By Addez in forum New To Java
    Replies: 4
    Last Post: 08-29-2009, 06:56 PM
  4. Array problems..
    By smokeviolent in forum New To Java
    Replies: 1
    Last Post: 04-17-2009, 06:45 AM
  5. Array problems
    By Hosticus in forum New To Java
    Replies: 2
    Last Post: 01-18-2009, 02:48 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •