joseph
joseph

Reputation: 11

How to print elements from multiple ArrayLists on the same line?

I get the below error:

C:\Area52\AndroidProgramming>javac -d . ex1.java ex1.java:27: error:

no suitable method found for println(Object,Object)

            System.out.println(players.get(0), batAvg.get(0));
                      ^
method PrintStream.println(Object) is not applicable
  (actual and formal argument lists differ in length)

Here is my code:

package one.exercise;

import java.util.*;

public class ex1
{
    public static void main(String[] args)
    {
        ArrayList players = new ArrayList();

        players.add("Joey");
        players.add("Thomas");
        players.add("Joan");
        players.add("Sarah");
        players.add("Freddie");
        players.add("Aaron");

        ArrayList batAvg = new ArrayList();

        batAvg.add(.333);
        batAvg.add(.221);
        batAvg.add(.401);
        batAvg.add(.297);
        batAvg.add(.116);
        batAvg.add(.250);

        System.out.println(players.get(0), batAvg.get(0));
        System.out.println(players.get(1)); //+ batAvg.get(1));
        System.out.println(players.get(2)); //+ batAvg.get(2));
        System.out.println(players.get(3)); //+ batAvg.get(3));
        System.out.println(players.get(4)); //+ batAvg.get(4));
        System.out.println(players.get(5)); //+ batAvg.get(5)); 
    }
}

Upvotes: 1

Views: 4716

Answers (3)

Gary
Gary

Reputation: 916

The issue is that you're trying to use the the println method on a PrintStream which takes only one argument.

See javadoc.

Instead of giving the two Strings you want as different arguments, you concat them together as demonstrated in the previous answers to have one argument and meet the requirements of println.

Upvotes: 0

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

You have two options:

  1. Concatenate, as already suggested.
  2. Use System.out.print. The is more flexible if you need to vary the number of lists. After the last item on the line, call System.out.println to end the line.

Upvotes: 0

Mike
Mike

Reputation: 2434

System.out.println(players.get(0) + ", " + batAvg.get(0));

Better yet...

for(int i = 0; i < players.size() && i < batAvg.size(); i++)
    System.out.println(players.get(i) + ", " + batAvg.get(i));

You can drop one of the two conditions (i < players.size() or i < batAvg.size()) if you can guarantee they'll always be the same size.

Upvotes: 4

Related Questions