1

I have a small program that reads a json file that gives the weather, time, temp, wind, ect. I need to calculate the average tempature for 2009 through 2015. The years are in an array, and are in length, around 60k. I am trying to write a small loop that will first find the position of the first instance of the year 2009 and then the last instance of the year 2009. Then I can run my average temp loop through that, but I am running into an issue as seen below.

place will be the index of the array. However, no matter how I run my code, it always equals -1, rather than giving me the position of the index in the array. Both arguments in the if statements are strings.

So what am I doing wrong?

String twozerozeronine = "2009";
int place = -1;
for (int a = 0; a < years.size(); a++){
    if (years.get(a) == twozerozeronine){
        place = 1; 
        break;
    }
}
System.out.println(place);
Tom
  • 16,842
  • 17
  • 45
  • 54
Sofelia
  • 109
  • 9
  • `if (years.get(a) === twozerozeronine)` Try this. – san A Mar 22 '17 at 11:48
  • 1
    @sanA Java does not have a triple-equals operator. – khelwood Mar 22 '17 at 11:53
  • `if (years.get(a) .equals(twozerozeronine))` – c0der Mar 22 '17 at 11:53
  • `if (years.get(a).equals(twozerozeronine))` Try this. Thanks for correction @khelwood – san A Mar 22 '17 at 11:55
  • thanks the .equals helped but then we noticed that we also had an error in our syntax that made it mess up! Solved now. – Sofelia Mar 22 '17 at 13:10
  • Hey Sofelia. I see you had a bit of a rough ride on SO recently. If you want any advice on using the platform or editing etiquette, feel free to ping me or [drop me an email](https://blog.jondh.me.uk/about/). – halfer Mar 04 '19 at 21:33

2 Answers2

0
years.get(a) == twozerozeronine

checks whether the object on the left side of the operator and the object on the right side of the operator are the very same. In your case they might be similar, but will never be the very same.

You will need to check whether they are similar instead:

years.get(a).equals(twozerozeronine)
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
-1

You can use equals() method to compare the value of the Strings.

Like: if ( years.get( a ).equals( twozerozeronine ) ){

The == operator compares the Object references (in your case, both are not equal) whereas equals() method compares the actual string values (in your case, the string values are "2009").

halfer
  • 19,824
  • 17
  • 99
  • 186
VNT
  • 934
  • 2
  • 8
  • 19