-1

I am completely stuck on this and need help.

I need to get the value if another value is equal to something.

Lets say my array is:

"people":[
    {"name": "David", "age": "30"}, 
    {"name": "Bob", "age": "20"}, 
    {"name": "Bill", "age": "30"}
]

I need to return the age if the name is lets say Bob. I have attempted to do it this way but to no avail.

String People = jsonPart.getString("people");
JSONArray arr = new JSONArray(People);

for (int h = 0; h < arr.length(); h++) {

    JSONObject jsonPart = arr.getJSONObject(h);

    String name = jsonPart.getString("name");

    if (name == "Bob") {

        String age = jsonPart.getString("age");

        break;

    }
}
DavidG
  • 3
  • 4

2 Answers2

1

Your problem is that you cannot do String comparisons in Java using the == operator. You must use String#equals so replace this line:

if (name == "Bob") {

with

if(name.equals("Bob")) {

See this link for more info:

https://www.baeldung.com/java-compare-strings and https://docs.oracle.com/javase/tutorial/java/data/comparestrings.html

Cody Caughlan
  • 32,456
  • 5
  • 63
  • 68
1

You can also do it like this:

If("Bob".equals(name))

to avoid NullPointerException if the name is null.

Akef
  • 339
  • 3
  • 13