1

I'm quite new to java and I've written the code to display the values of the following parallel arrays:

short[] Years = {1995, 1997, 1998,1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012};

String[] Months = {"January", "February", "June", "January", "March", "June", "July", "August", "September", "March", "May", "January", "March", "July", "November", "March", "June"};

Currently when I run it, they display on top each other. I'm trying to get it to display side by side. How can I do that?

This is the piece of code for displaying them:

System.out.println("Years");
for(short temp: years)
{
System.out.println(temp);
}
System.out.println("Months");
for(String temp: months)
{
System.out.println(temp);
}
Ryan
  • 5,644
  • 3
  • 38
  • 66
user2297518
  • 35
  • 1
  • 3
  • 8

3 Answers3

2

try this:

int length = Years.length > Months.length ? Months.length : Years.length;
for(int index = 0; index < length; index++) {
    System.out.println(Years[index] + '\t' + Months[index]);
}

And i suggest reading this

Marco Forberg
  • 2,634
  • 5
  • 22
  • 33
  • it works for displaying them side by side, but for each year it posts all the months. eg 1995 January, 1995 February and so on – user2297518 Apr 19 '13 at 06:59
2

If they are of equal length:

for (int i = 0; i < Years.length; i++) {
    System.out.println(Years[i] + '\t' + Months[i]);
}
ghdalum
  • 891
  • 5
  • 17
  • Please notice that this will give you an `OutOfBounds exception` if the two Arrays isn't of equal length – John Snow Apr 19 '13 at 07:06
1

You can do it like this:

 short[] years = {1995, 1997, 1998,1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012};
    String[] winners = {"January", "February", "June", "January", "March", "June", "July", "August", "September", "March", "May", "January", "March", "July", "November", "March", "June"};
    System.out.println("Years"+"\t"+"Premiers");
    int i = years.length-1;
    int j= winners.length-1;
    int  k=0;
int l=0;
    do{
            i--;
            j--
        System.out.println(years[k++]+"\t"+winners[l++]);
    }while(i>=0 || j>=0);

You will found the output like:

Years   Premiers
1995    January
1997    February
1998    June
1999    January
2000    March
2001    June
2002    July
2003    August
2004    September
2005    March
2006    May
2007    January
2008    March
2009    July
2010    November
2011    March
2012    June
Shreyos Adikari
  • 12,348
  • 19
  • 73
  • 82