-2

Can someone please tell me what I'm doing wrong here.

I'm trying to access a Map and put the keys which start with the letter "N" in an array. However I'm getting a Cannot find symbol error referring to charAt(int)? Intellij is suggesting me to create an abstract class for chartAt?

import java.util.Map;
public class RoadNetwork {

    String[] nodeList;

    public void storeNodes(Map<String, Element> result) {

        int counter =0;
        nodeList = new String[result.size()];

        //Cycle through Map to find elements which are Nodes
        for (int i = 0; i < result.size(); i++) {
            //if Node, then add it to array
            if (result.get(i).charAt(0) == "N") {
                nodeList[i] = String.valueOf(result.get(i));
                counter++;
            }
        }
        System.out.println("Nodes Array Length" + counter);
    }
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Anthony J
  • 551
  • 1
  • 9
  • 19
  • 2
    `Element` doesn't have a `charAt(int)` method and `result.get(i)` returns of course the *value*, not the key. You're also trying to compare the result of `charAt()` to the String literal `"N"` instead of the character literal `'N'`. – Kayaman Apr 05 '17 at 09:42

2 Answers2

1

Your Map is having key as String and you are passing int in line if (result.get(i).charAt(0) == "N") { so instead of passing result.get(int) pass result.get(String)

For checking the keys starting from N do this :

int counter =0; nodeList = new String[result.size()];

//Cycle through Map to find elements which are Nodes
int i = 0;
    //if Node, then add it to array
  for(String key : result.keySet())
  {
  if (key.charAt(0) == 'N') {
        nodeList[i] = key;
        counter++;
    }
  }

System.out.println("Nodes Array Length" + counter);
Gourav
  • 9
  • 2
0

Problems appears to be with

if (result.get(i).charAt(0) == "N") {

May be you want to retrieve key but get() method returns value, which is of type Element, which doesn't have method charAt().

You may try something like:

for (String key:result.keySet()) {
        //if Node, then add it to array
        if (key.charAt(0) == 'N') { //'N' and not "N"
            nodeList[i] = String.valueOf(result.get(key));
            counter++;
        }
    }
santosh-patil
  • 1,540
  • 1
  • 15
  • 29