Page 1 of 2 12 LastLast
Results 1 to 20 of 23
  1. #1
    VinTiger is offline Member
    Join Date
    Feb 2009
    Posts
    32
    Rep Power
    0

    Default Multi-dimensional array

    Hi,

    I was wondering if someone could help explain the difference between an array and a multi-dimensional array? How do I for instance let a user enter info into an multi-dimensional array, compared to a single array?

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default

    Java doesn't have a built in type representing a multidimensional array as such. Rather they are implemented as an array-of-arrays.

    See, for instance, Java: Two-dimensional arrays as arrays of arrays.

    How do I for instance let a user enter info into an multi-dimensional array, compared to a single array?
    It's no different: get the array indices and the value and assign.

    Java Code:
    int r = ... // Scanner's nextInt(), or BufferedReader methods etc...
    int c = ... 
    int val = ...
    
        // array created as in the page linked to
    my2dArray[c][r] = val;

  3. #3
    VinTiger is offline Member
    Join Date
    Feb 2009
    Posts
    32
    Rep Power
    0

    Default

    thanks, I'm still kind of stuck though tryong to make a simple program work. I'm compleately new to programming so I'm sure my errors are easy to detect bt someone who knows this stuff. This is my code so far:

    -----------------------------------------------------------------------

    import java.util.Scanner;

    import java.io.*;

    public class PhoneBook9

    {

    public static void main(String[] args)

    {

    int row = 2;
    int col =2;

    String[][] phone; //Declares multi-dimensional array
    phone = new String[row][col]; //sets aside memory for ten entries



    Scanner in = new Scanner(System.in);

    System.out.print("Enter Name:");
    for(int i=0; row<3; i++) {


    System.out.println("Enter number:");
    for (int j=0; col<3; j++) {


    phone[0][0] = in.nextLine();
    phone[0][1] = in.nextLine();
    phone[1][0] = in.nextLine();
    phone[1][1] = in.nextLine();
    }

    }


    System.out.println(phone[row][col]);



    }
    }

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You need to think about what each item in the array is going to hold before you start coding. I am going to assume that each row holds two columns -- two Strings -- one for name and one for number (not a great design by the way, but I'm guessing that you're stuck with it).

    So that means that in row i, column 0 will hold the name and column 1 the number. So loop through each row (the outer loop), then in the inner loop isn't really a loop since you're not repeating yourself here -- you're getting different type of data for each column. Instead of a loop you'll get first a name which you'll place in spot[i][0], and then the number which is placed in spot[i][1].

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Also, when posting code here, please use code tags so that your code will retain its formatting and thus will be readable -- after all, your goal is to get as many people to read your post and understand your code as possible, right?

    To do this, highlight your pasted code (please be sure that it is already formatted when you paste it into the forum; the code tags don't magically format unformatted code) and then press the code button, and your code will have tags.

    Another way to do this is to manually place the tags into your code by placing the tag [cod&#101;] above your pasted code and the tag [/cod&#101;] below your pasted code like so:

    Java Code:
    [cod&#101;]
      // your code goes here
      // notice how the top and bottom tags are different
    [/cod&#101;]

  6. #6
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default

    (A couple of things: when you post code highlight the code and then click the code button labelled # so that the code is readable. Also say what the problem is. If the code doesn't compile and you can't understand the compiler message, post the message. If the program compiles but doesn't do what you expect or intend when you run it, say what you expect or intend and what the program actually does.)

    First of all, notice that Java arrays are "zero-based" - that is, the first index starts at zero. You set up the array as being 2x2 which suggests that you want 4 entries. But then your loops go from 0 to less than 3, which would be a total of 9 entries.

    Inside the inner for loop ("for int j=0...") you would typically set just a single entry.

    Did you read the page I linked to?

    Maybe the following 1-D case will help:

    Java Code:
    import java.util.Scanner;
    
    public class PhoneBook
    {
        public static void main(String[] args)
        {
                // I'll use capitals for a number that is never going
                // to change
            int ROW_SZ = 5;
    
                // declare and initialise the array
            String[] phone = new String[ROW_SZ];
    
            Scanner in = new Scanner(System.in);
    
                // my loop variable - row - is more descriptive than i
            for(int row=0; row<ROW_SZ; row++) {
                    // the prompt goes *inside* the for loop so that
                    // it will be repeated
                System.out.print("Enter Name:");
                    // there is just one assignment to the array
                phone[row] = in.nextLine();
            }
    
            System.out.println("Name number 3:");
            System.out.println(phone[3]);
        }
    }
    (in fact the variable I called row was really column index, but nevermind.)

    I would suggest that you assure yourself that you understand exactly what each line of the 1-D case is doing before tackling the 2-D case.

  7. #7
    VinTiger is offline Member
    Join Date
    Feb 2009
    Posts
    32
    Rep Power
    0

    Default

    Yes, i did read it, and I'm still readin it accually:)

    well, I'm trying to understand what all the code is doing, and with 1-d arrays I can get my program to run. I guess my biggest problem right now is to understand how I can have a "user" enter a name, and then a phone nr instead of having to first enter all the names, and then phone numbers. I realize that as Fubarable mentioned I need to loop through one row at the time, but how do I do that?

  8. #8
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default

    The code I posted goes through the array and inside the for loop it:
    * prompts the user
    * gets their input
    * assigns their input to the right place in the array

    (The 3 things are done in the 2 lines of the for loop.)

    In your case you also want to go thru the array and
    * prompt the user
    * get their input
    * assign their input to the right place in the array
    * prompt the user again
    * get their input again
    * assign their input to a different place in the array

    Similar code, but with 6 things being done inside the for loop (with 4 lines).

  9. #9
    VinTiger is offline Member
    Join Date
    Feb 2009
    Posts
    32
    Rep Power
    0

    Default

    ok, I tried adding the rest of the code to make it a 2d array, but I'm getting an error when I try running the code that says: Exeption in thread "Main" java.lang.ArrayIndexOutOfBoundsExeption.


    ----------------------------------------
    import java.util.Scanner;

    public class PhoneBook
    {
    public static void main(String[] args)
    {

    int r = 5;
    int c = 2;


    String[][] phone = new String[r][c];

    Scanner in = new Scanner(System.in);


    for(int row=0; row<r; row++) {
    for(int col=0; col<c; col++) {

    System.out.print("Enter Name:");

    phone[r][c] = in.nextLine();

    System.out.print("Enter Number:");

    phone[r][c] = in.nextLine();

    }
    }
    System.out.println("Names and number:");
    System.out.println(phone[r][c]);
    }
    }

  10. #10
    eldris is offline Member
    Join Date
    Mar 2009
    Posts
    4
    Rep Power
    0

    Default

    Surely
    Java Code:
    System.out.println(phone[row][col]);
    will get you an array out of bounds error? It should be

    Java Code:
    System.out.println(phone[row-1][col-1]);
    if you're trying to print the last element.


    Also, your for loops will be infinate, as row < 3 always. Use

    Java Code:
    for(int i = 0; i < row; i++) {
    //loop body
    }
    and the same for the inner loop. This will also give you the correct indexing if you use [i][0] etc as Fubarable said. As indexing of arrays starts at 0, the last element will have index array size - 1. That's why the println was wrong too :)


    [EDIT] Didn't see your lastest post VinTiger. It seems your problem left is the last print statement, needing

    Java Code:
    System.out.println(phone[r-1][c-1]);
    [/EDIT]
    Last edited by eldris; 03-01-2009 at 05:58 AM.

  11. #11
    VinTiger is offline Member
    Join Date
    Feb 2009
    Posts
    32
    Rep Power
    0

    Default

    Sorry, used the wrong tags for the code

  12. #12
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default

    Be sure to test this.

    How many names do you enter? How many phone numbers? And how many name/number pairs do you expect to store in your array?

  13. #13
    VinTiger is offline Member
    Join Date
    Feb 2009
    Posts
    32
    Rep Power
    0

    Default

    I want to enter and store five names with phone numbers. So 5 rows and 2 columns should allow for this, right?

    I also want to be able to print the list of names with phone numbers.

  14. #14
    VinTiger is offline Member
    Join Date
    Feb 2009
    Posts
    32
    Rep Power
    0

    Default

    I tried changing it to [r-1][c-1] eldris, but I still got the error message.

  15. #15
    eldris is offline Member
    Join Date
    Mar 2009
    Posts
    4
    Rep Power
    0

    Default

    Java Code:
    System.out.print("Enter Name:");
    
    phone[r][c] = in.nextLine();
    
    System.out.print("Enter Number:");
    
    phone[r][c] = in.nextLine();
    Here you are overwriting the name entered. If you want them to be the same string you'll need something like

    Java Code:
    System.out.print("Enter Name:");
    
    phone[r][c] = in.nextLine();
    
    System.out.print("Enter Number:");
    
    phone[r][c] += " " + in.nextLine();

    To print out the list, do a similiar nesting of loops like you did for input, but with print statements instead.

  16. #16
    eldris is offline Member
    Join Date
    Mar 2009
    Posts
    4
    Rep Power
    0

    Default

    Posted at the same time again, sorry ^^; I'll see if I can work out what else is causing the out of bounds exception

  17. #17
    eldris is offline Member
    Join Date
    Mar 2009
    Posts
    4
    Rep Power
    0

    Default

    Ah, ok. It's because in the for loop assignment statements you're using r and c, where you should be using row and col for the indexing, as those are the ones the loops increment

  18. #18
    VinTiger is offline Member
    Join Date
    Feb 2009
    Posts
    32
    Rep Power
    0

    Default

    You were right, I was using r and c instead of row and col. This time I was able to compile and run the program. However, it let me enter ten names and ten phone numbers, and the it threw me the same error meassage: ArrayIndexOutOfBoundsExeption.

  19. #19
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default

    However, it let me enter ten names and ten phone numbers
    Since the array was only designed to store five name/phone pairs, I suggest you sort this out before trying to print out the array contents.

    Go through your code saying the loop variable values out loud, or writing them down or something, to see why you end up entering twice as many name/phone pairs as you intended.

    (There are various ways to correct this. One of them was hinted in an earlier reply of mine: use a single for loop.)

  20. #20
    VinTiger is offline Member
    Join Date
    Feb 2009
    Posts
    32
    Rep Power
    0

    Default

    Shouldn't the names and the numbers be stored in different columns in the program?, and if so, can I specify this in this statement:

    phone[r][c] = in.nextLine();

    can I choose column 2 for instance within the brackets, such as [c1] or something like that?

    Is it possible that the program somehow can store both a name and a number in the same element of the array?, and that this is the reason that I get to enter ten names and ten mumbers before I get a error message?

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 7
    Last Post: 09-27-2011, 12:29 AM
  2. two-dimensional array
    By kHim in forum New To Java
    Replies: 4
    Last Post: 11-16-2008, 08:21 PM
  3. Multi dimensional Array
    By Preethi in forum New To Java
    Replies: 1
    Last Post: 07-09-2008, 04:34 PM
  4. Replies: 2
    Last Post: 01-07-2008, 08:45 PM
  5. Help with array multi-dimensional
    By barney in forum New To Java
    Replies: 1
    Last Post: 07-31-2007, 09:00 PM

Posting Permissions

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