# 2D Arrays

• 03-17-2011, 12:10 AM
NixasMuraki
2D Arrays
In the following program for the two dimensional arrays I want to get the same output as the one dimensional arrays, but how do I get "biome" and "precipitation" every time? I don't think that I can split it up the way I have where I have secdim[j] and secdim[i], because when splitting it up I end up with strange symbols and such. So how do I accomplish this? Also if you see anything else wrong, feel free to throw it out there. Thanks in advance!

import java.util.*;

public class ArrayDimensions
{
public static void main(String[]args)
{
System.out.println("Using two separate one dimensional arrays, we get this output.");

//declaring and initializing on the same line
int rain[]={32,56,12,78};//amount of precipitation
String enviro[]={"Taiga","Deciduous","Desert","Rainforest"};//biome that has that amount of precip.

for(int i=0; i<enviro.length;i++)
{
System.out.println("Biome:"+enviro[i]+", Amount of Precipitation:"+rain[i]+"\n");
}
//now we can do the same thing using a 2D array
//see if a 2d array can have two different types of datatypes
System.out.println("Now we will do the same thing only with a two dimensional array");
String secdim[][]={{"Taiga","Deciduous","Desert","Rainforest"},
{"32","56","12","78"}};
//need to use a nested for loop

for(int i=0; i<secdim.length; i++)
{
for(int j=0;j<secdim[j].length; j++)
{
System.out.println("Biome:" +secdim[j]+" ,Amount of Precipitation:"+secdim[i]);
}
System.out.println();
}
• 03-17-2011, 12:18 AM
sunde887
I believe your strange symbols are the default array toString, in a 2d array each I will contain an array itself so printing item I of a 2d array prints the toString, which looks something like.

ClassName@18afe72

When specifying an array index in a 2d arrays you need something like

Code:

`Array[I][j]`
• 03-17-2011, 12:24 AM
NixasMuraki
Oh I see, so it should be secdim[I][j]?
• 03-17-2011, 12:32 AM
sunde887
The I doesn't have to be capitalized, my phone auto did that. And that's just how to index, you need to figure out how to index correctly for the output you want
• 03-17-2011, 12:59 AM
sunde887
You can do it that way, however; 2d indexing will work fine as well.
• 03-17-2011, 09:53 AM
DavidG24
Quote:

Originally Posted by NixasMuraki
//now we can do the same thing using a 2D array
//see if a 2d array can have two different types of datatypes

Just to answer your question, a multidimensional array in Java can only be of one Object-Type. There are plenty of other types of Collection Types that will allow for groupings of different Object types, however, in my experience - it is generally advised to have everything of one type.

Cheers,

David