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.