0

I need little help on a homework assignment. I have to create a 10 by 10 ArrayList, not an array. 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;
    }
  }
}
2
  • Please fix the format if you want anyone to look at this. Commented Nov 20, 2009 at 16:18
  • just so you know I made my students do a similar thing... so your instructor is not the only insane one :-) (in my case an array of arrays would make no sense however!) Commented Nov 20, 2009 at 16:36

2 Answers 2

1

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);
            }

        }
     }
Sign up to request clarification or add additional context in comments.

1 Comment

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.
0

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("");
      }
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.