For your assignment please use a nested for loop to create an ArrayList that contains 10
ArrayList<String>
, . Each individual list will contain 10 elements , for a total of 100 elements, The first list will contain the String objects "1" to "10". The last ArrayList will contain the String objects "91" to "100". To retrieve a specific element use something like this:
twoD.get(i).get(j); This will retrieve the jth element from the ith ArrayList. Use an additional nested for loop to print the numbers 1 to 100. There should be 10 rows and 10 columns, beginning with 1 and ending with 100.
This is what I have to do, I am having a hard time trying to do this by following these exact instructions. The code that I have so far prints the output but I do not think it is correct because it was just one for loop.
ArrayList<ArrayList<String>> twoD = new ArrayList<ArrayList<String>>();
System.out.println("Numbers 1 through 100 ");
for (int n = 1; n <= 100; n++) {
System.out.print(" " + n);
if (n % 10 == 0)
System.out.print("\n");
}
}
}
The assignment says to use nested for
loops to make 10 lists of 10 numbers each. Each for
loop needs to iterate 10 times to get 10 x 10 = 100 total iterations. You can use each iterator to calculate the value to add to the lists.
Since this looks like homework, I'll leave some things out.
ArrayList<ArrayList<String>> twoD = new ArrayList<ArrayList<String>>();
for (int n = 0; n < 10; n++) {
// Create and add a new list here
for (int m = 0; m < 10; m++) {
// Use n and m to calculate the current number
// Then convert to string and add that to the most recently created list
}
}
To print the list, you can use another nested loop:
for (int n = 0; n < 10; n++) {
for (int m = 0; m < 10; m++) {
System.out.printf("%s ", twoD.get(n).get(m));
}
System.out.println();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.