-1
protected int getGewichtung(String company)
{
    int index;

    for (HashMap<String,String> i : top3Compland) 
    {
        String test = String.join(_name, i.keySet());
        System.out.println(test);

        if (test == company) 
        {
            index = top3Compland.indexOf(i);
            
        } 
        else 
        {
            index = -5; 
        }
    }
    
    return index;
}

I have checked with print statements whether it is entering the for-loop at all. But all the keys are being printed out so it does enter it and also the conversion to a string does take place and as I am at first putting only valid strings to the function it also must enter the if statement for sure but if even it doesn't then it would be enter the else statement and initialize it with a number so it should't be complaining about the variable "index" possibly not being initialized. What am I overseeing?? Thank you for your help!

updated Version: I improved some flaws, but the same error is arising. But I cannot fathom a case in which index is not being initialized...

    protected int getGewichtung(String company)
{
    int index;


   
    if (top3Compland.size() > 0 && top3Compland != null) 
    {
        for (HashMap<String,String> i : top3Compland) 
        {
            String test = String.join(_name, i.keySet());
            System.out.println(test);

            if (test.equals(company)) 
            {
                index = top3Compland.indexOf(i);
            
            } 
       
        }
    }
    else
    {
        index = -5; //company not found
    }
    return index;
}
  • 6
    what do you think would happen if `top3Compland` was empty? Also `test == company` is not the way to comapre Strings in Java – Scary Wombat Dec 19 '22 at 00:58
  • 1
    Not the stated problem, but -- if top3Compland has 42 entries, index is computed for the first 41 entries but otherwise ignored; the return value depends only on the last entry, and which entry that might be is arbitrary given hashed keys. This seems like not very useful code. – access violation Dec 19 '22 at 01:17
  • 1
    Also also, do not compare strings with `==`. Use `equals`. – access violation Dec 19 '22 at 01:18

1 Answers1

5

You do have an initialization in both if/else statements, however this only applies when you enter the foreach loop. When top3Compland is empty the program doesn't enter the loop and the variable index is never initialized.

  • what about now? now that I have conditions for it to enter the if loop (not empty and not null). and in all other cases it would go to the else block, in which case it would get the value -5 – Student_1899 Dec 19 '22 at 10:59
  • 1
    @Student_1899 well, in this case, if the program goes through the foreach loop but not the if block inside it the variable `index` will never be initialized – Salvador Palma Dec 19 '22 at 14:33