tags:

views:

284

answers:

2

I need little help on a homework assignment. I have to create a 10 by 10 ArrayList, not an array that would make too much sense. This is what I have and I just need a hint on how to do a for loop to add the date to the 2d ArrayList. By the way this is for putting data that are grades; going from 100 to 82. (Yes I know it is homework but need to be pointed in the correct direction)

   public void q6()
   {
       //part a
       ArrayList<ArrayList<Double>> grades;
       //part b
       grades = new ArrayList<ArrayList<Double>>(10);
       //second dimension
       grades.add(new ArrayList<Double>(10));
       for(int i = 0; i < 10; i++)
       {
           for(int j = 0; j < 10; j++)
           {
               //grades.get().add(); Not sure what to do here?
               //If this was an array I would do something like:
               // grades[i][j] = 100 -j -i;
            }

        }
     }
+1  A: 

Something like this could do?

   public void q6()
   {
       //part a
       ArrayList<ArrayList<Double>> grades;
       //part b
       grades = new ArrayList<ArrayList<Double>>(10);
       //second dimension
       for(int i = 0; i < 10; i++)
       {
           List<Double> current = new ArrayList<Double>(10);
           grades.add(current);

           for(int j = 0; j < 10; j++)
           {
               current.add(100 - j - i);
            }

        }
     }
Rickard
Thanks for the edit and for help guys.
Size_J
Thanks for the hlep. I was missing that I need to create the second ArrayList object inside the first for loop. The nested for loops threw me off the trail I think. Thanks for the help again.
Size_J
A: 

Given the code, all you left to do is change it a little to receive 10x10 matrix.

public class Main
{
   public static final int ROW_COUNT = 5;
   public static final int COL_COUNT = 10;

   public static void main(String[] args)
   {
      ArrayList<ArrayList<Double>> grades = new ArrayList<ArrayList<Double>>();

      for (int i = 0; i < ROW_COUNT; i++)
      {
         ArrayList<Double> row = new ArrayList<Double>();

         for (int j = 0; j < COL_COUNT; j++)
         {
            row.add(100.0 - j - i);
         }

         grades.add(row);
      }

      for (int i = 0; i < ROW_COUNT; i++)
      {
         for (int j = 0; j < COL_COUNT; j++)
         {
            System.out.print(grades.get(i).get(j));
            System.out.print(", ");
         }

         System.out.println("");
      }
   }
}
Mykola Golubyev