3 Replies - 3252 Views - Last Post: 11 April 2014 - 12:06 AM Rate Topic: -----

#1 gilbertodemelo   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 21-October 13

Putting values from a 2D Array to a HashMap

Posted 09 April 2014 - 06:09 PM

Hey guys

I was wondering if I someone could help me with this.

I have a 2D array and the elements are listed as follows:

outlook temperature humidity windy gooutside
sunny hot high false n
overcast hot high false y
....

I need to put these values into a HashMap, where the elements of the first row are the keys and the elements from row 1 to n-1 are the values. Does anyone know what would be the best way to make sure the key and values are matched correctly?

Here is what I have:

String[][] array = new String[numberOfRows][numberOfCols];
HashMap<String, String> map = new HashMap<String, String>();
for(int rows = 0; rows < (numberOfRows * numberOfCols); rows++) {
    for(int cols = 0; cols < array[i].length; cols++} {

       map.put(array[0][cols], array[rows*cols][col];
    }
}



I keep getting the out of bounds error.

thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: Putting values from a 2D Array to a HashMap

#2 mike73   User is offline

  • D.I.C Addict
  • member icon

Reputation: 250
  • View blog
  • Posts: 918
  • Joined: 24-April 10

Re: Putting values from a 2D Array to a HashMap

Posted 10 April 2014 - 12:08 AM

you are trying to access more elements than your array has. To cycle through each element in your array you would use:
for(int rows = 0; rows < numberOfRows; rows++) {
    for(int cols = 0; cols < numberOfCols; cols++} {
       System.out.println(array[rows][cols]);
    }
}

You are multiplying rows * cols and numberOfRows * numberOfCols which is causing your code to to attempt to access elements that just don't exist.
Was This Post Helpful? 0
  • +
  • -

#3 gilbertodemelo   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 21-October 13

Re: Putting values from a 2D Array to a HashMap

Posted 10 April 2014 - 04:15 PM

Hi, thank you for the reply. However, I am not trying to print what is in the 2D array. Like I said, I need to put the values in a hashmap, where the keys are the words in the first row of the array and the values for each key will be the values in the same row in the array.

Thank you
Was This Post Helpful? 0
  • +
  • -

#4 mike73   User is offline

  • D.I.C Addict
  • member icon

Reputation: 250
  • View blog
  • Posts: 918
  • Joined: 24-April 10

Re: Putting values from a 2D Array to a HashMap

Posted 11 April 2014 - 12:06 AM

I understand that. My example was to show why your code is going out of bounds, and the correct way to stay in bounds. You seem to have the logic of putting in to a hashmap already.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1