我是java的新手,我编写了代码来显示以下并行数组的值:
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"};
目前,当我运行它时,它们彼此显示在一起。我试图让它并排展示。 我怎么能这样做?
这是显示它们的代码:
System.out.println("Years");
for(short temp: years)
{
System.out.println(temp);
}
System.out.println("Months");
for(String temp: months)
{
System.out.println(temp);
}
答案 0 :(得分:2)
试试这个:
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]);
}
我建议阅读this
答案 1 :(得分:2)
如果长度相等:
for (int i = 0; i < Years.length; i++) {
System.out.println(Years[i] + '\t' + Months[i]);
}
答案 2 :(得分:1)
你可以这样做:
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);
您将找到如下输出:
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