0

I have a small program that hold pairs of states and their capitals in 2D array. Below this program:

public class StateCapitals {

public static void main(String[] args) {
    String[][] answers = {
            {"Alabama", "Montgomery"},
            {"Alaska", "Juneau"},
            {"Arizona", "Phoenix"},
            {"Arkansas", "Little Rock"},
            {"California", "Sacramento"},
            {"Colorado", "Denver"},
            {"Connecticut", "Hartford"},
            {"Delaware", "Dover"},
            {"Florida", "Tallahassee"},
            {"Georgia", "Atlanta"}
    };


    int correctCount = 0;

    for (int i = 0; i < answers.length; i++) {


        System.out.print("What is the capital of " + answers[i][0]);

        Scanner input = new Scanner(System.in);

        String userInput = input.nextLine();



        for (int j = 0; j < answers[i].length - 1; j++) {
            System.out.println("The correct answer should be " + answers[i][j + 1]);

            if(userInput.equals(answers[i][j + 1]))
                correctCount++;

        }


    }

    System.out.println("The correct count is " + correctCount);
    }
}

I need to replace regular 2D array with List<List<String>> super2dArray = new ArrayList<ArrayList<String>>().

I found some threads on stackoverflow how to add array that I want. Here is links: How to create an 2D ArrayList in java? andHow do I declare a 2D String arraylist?. But these discussions didn't explain how to add elements in each ArrayList. The best that I can do to create new ArrayList then add some elements and finally attached ArrayList to another one. They didn't explain how to add elements to 2D ArrayList.

Community
  • 1
  • 1
rob111
  • 1,249
  • 1
  • 13
  • 18

1 Answers1

0

Here a way easier example :)

Notice that I give a fixed initial length to the constructor of the ArrayList as we already know the length of the array.

List<List<String>> myListOfListOfString = new ArrayList<List<String>>(answers.length);

for(String[] array : answers)
    myListOfListOfString.add(Arrays.asList(array));

See documentation for more details.

Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76