Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Understanding arrays in java

  1. Dec 8, 2007 #1
    I just have a question about my "solution" to a problem. The question says to write a value returning method that returns the number of rows in a two-dimensional array of doubles.

    It should be simple enough and so I did it like this:

    Code (Text):
    public int countRows()
    {
        int x;
        x = 0;
        for (int i = 1; i < arrayOne.length; i ++)
            {
                if( i > x)
                x=i;
            }
                x = x+1;
    }
    arrayOne is the encapsulated array in a class. It just loops through the array and assigns the next i value to the greatest value.

    I tested that and it seems to work but it's one of those problems where there probably is a better way. The next question I have is to return the number of columns with two elements, which is why I thought it would be a good idea to get ready to have an if statement in there. Does this look OK or is there a far easier solution?
     
  2. jcsd
  3. Dec 8, 2007 #2

    KTC

    User Avatar

    I don't understand what you wanting with returning the number of rows in 2D array as you know it can varies.

    Anyhow.
    Code (Text):
    int x;
        x = 0;
        for (int i = 1; i < arrayOne.length; i ++)
    Why are you counting from 1?
     
  4. Dec 8, 2007 #3
    I was going to point this out. It is kind of a weird problem but it does come from a programming book. This is just the solution I came up with, and I wondered if anybody else had a better one. I should note it returns x, of course.

    Isn't it obvious? Program efficiency.
     
  5. Dec 8, 2007 #4

    KTC

    User Avatar

    Having actually looked at what you're doing inside that loop....

    :confused:

    If what're you're returning is just
    Code (Text):
    arrayOne.length
    then why not actually just
    Code (Text):
    return arrayOne.length
    ? What's with the loop at all??
     
  6. Dec 8, 2007 #5
    This.

    Code (Text):
    public int countRows(){
        return arrayOne.length;
    }
    Alternatively, if you wanted the number of rows in a two dimensional array, you would use 'return arrayOne[0].length'. The 'sub' arrays length is indexed by a zero address.

    What's this talk about that the number of rows in an array can vary? From my understanding, once the the arrays size(s) have been set, it cannot change. If you're talking about the number elements of the array being populated (that have replaced the initialized values), then you can simply set up a counter for that.
     
    Last edited: Dec 8, 2007
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Understanding arrays in java
Loading...