1

I've been working on some code to try to make sure I understand all of the ways to use ArrayLists and just some things I've been working on when I compile this code I get three errors for each "girlsNames.get(#)" on the girlsNames variable. I only get errors when I use the .get command and not when I use .add. tried assigning each "girlsNames.get()" to a variable then using that in the main method instead but it still doesn't work... I can't figure out the problem!

import java.util.ArrayList;

class List {
  public void babyNames(){
    ArrayList<String> girlsNames = new ArrayList<String>(3);
    girlsNames.add("Jennifer");
    girlsNames.add("Blorjek");
    girlsNames.add("Robby");
    }
  public static void main(String[] args) {
    if(args[0] == girlsNames.get(0))
    { System.out.println("Hello guardian of Jennifer");
    }
    else if(args[0] == girlsNames.get(1))
    { System.out.println("Hello guardian of Blorjek");
    }
    else if(args[0] == girlsNames.get(2))
    { System.out.println("Hello guardian of Robby");
    }
    else System.out.println("you may not enter the sanctuary");
  }

}
AurumTechie
  • 166
  • 3
  • 14
  • 3
    Use `equals()` method instead of `==` – Fenio May 28 '20 at 04:07
  • 2
    `girlsNames` is a local variable in `void babyNames()` and not visible to your `main` – Phu Ngo May 28 '20 at 04:11
  • Use `equals()` because `==` compare the string that belongs to the same pool. – Deep Dalsania May 28 '20 at 04:15
  • Welcome to Stack Overflow. When you get an error make sure to include the exact error in your question's description. Also try to be as specific and clear as you can be when asking for other's help – ***be concise***. And format your code for readability. Just a hint: Get a Java IDE (like IntelliJ) and learn to use it. Have a look at [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Ivo Mori May 28 '20 at 04:55

1 Answers1

2

== will compare references of String objects which could be different even if the value of both String objects is same. Use equals.