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?
Printable View
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?
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.
It's no different: get the array indices and the value and assign.Quote:
How do I for instance let a user enter info into an multi-dimensional array, compared to a single array?
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;
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]);
}
}
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].
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 [code] above your pasted code and the tag [/code] below your pasted code like so:
Code:[code]
// your code goes here
// notice how the top and bottom tags are different
[/code]
(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:
(in fact the variable I called row was really column index, but nevermind.)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]);
}
}
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.
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?
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).
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.
----------------------------------------
Quote:
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]);
}
}
Surely
will get you an array out of bounds error? It should beCode:System.out.println(phone[row][col]);
if you're trying to print the last element.Code:System.out.println(phone[row-1][col-1]);
Also, your for loops will be infinate, as row < 3 always. Use
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 :)Code:for(int i = 0; i < row; i++) {
//loop body
}
[EDIT] Didn't see your lastest post VinTiger. It seems your problem left is the last print statement, needing
[/EDIT]Code:System.out.println(phone[r-1][c-1]);
Sorry, used the wrong tags for the code
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?
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.
I tried changing it to [r-1][c-1] eldris, but I still got the error message.
Here you are overwriting the name entered. If you want them to be the same string you'll need something likeCode:System.out.print("Enter Name:");
phone[r][c] = in.nextLine();
System.out.print("Enter Number:");
phone[r][c] = in.nextLine();
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.
Posted at the same time again, sorry ^^; I'll see if I can work out what else is causing the out of bounds exception
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
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.
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.Quote:
However, it let me enter ten names and ten phone numbers
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.)
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?