-2

How can I print the contents of an ArrayList in a specific way, in Java? For example:

System.out.println("A        B");
System.out.println("100     100");
System.out.println("200     200");
System.out.println("300     300");

How can I do this with an ArrayList?

I write the array list like this:

ArrayList mathChoices = new ArrayList(3); 
mathChoices.add("100");
mathChoices.add("200");
mathChoices.add("300");

ArrayList historyChoices = new ArrayList(3);
historyChoices.add("100");
historyChoices.add("200");
historyChoices.add("300");

And it prints out like this:

Math        History
[100, 200, 300] [100, 200, 300]

I want to print out "MATH" and then "HISTORY" with vertical columns of 100,200,300 under each word. It is supposed to be like the questions in the game show Jeopardy.

4

1 回答 1

1

我同意评论,所以这是更新的答案:

System.out.println(String.format("%-20s %s" , "Mathematics", "History" ));

for (int i = 0; i<3; i++)
{
    System.out.println(String.format("%-20s %s" , mathChoices.get(i), historyChoices.get(i)));    
}

输出将按照您的要求。

于 2013-08-23T00:41:45.533 回答