1. Member
Join Date
Jan 2011
Posts
11
Rep Power
0

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();
}

2. 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

Java Code:
`Array[I][j]`
Last edited by sunde887; 03-16-2011 at 11:21 PM.

3. Member
Join Date
Jan 2011
Posts
11
Rep Power
0
Oh I see, so it should be secdim[I][j]?
Last edited by NixasMuraki; 03-16-2011 at 11:27 PM. Reason: other person made their post clear

4. 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

5. You can do it that way, however; 2d indexing will work fine as well.

6. Member
Join Date
Apr 2009
Posts
49
Rep Power
0
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