jeudi 30 septembre 2021

Unable to change the value of variable inside for-loop & if-else statement in Java

I'm working on a java function involving for-loop and if-else statement. and I have a need to change the value of a flag variable according to the conditions in multiple iterations. I declared a variable named flag and wants to change according to the condition in each iteration. And I need to print the value of the flag variable at the end of each iteration. But while I printing the variable it shows an error that the variable isn't initialized. If I gives it an initial value, it prints the initial value all the time, not the value manipulated inside the if-else statement. I can't initialize the flag variable inside the for-loop according to my requirement. Below is my code:

    int flag;

    for(int i=0; i< fileOneLines.length; i++){
        diffs = diffMatchPatch.diffMain(fileOneLines[i],fileTwoLines[i]);
        diffMatchPatch.diffCleanupSemantic(diffs);
        for (DiffMatchPatch.Diff aDiff : diffs) {
            if(aDiff.operation.equals(DiffMatchPatch.Operation.INSERT)){
                flag = 1;
            }
            else if(aDiff.operation.equals(DiffMatchPatch.Operation.DELETE)){
                flag = 2;
            }
            else if(aDiff.operation.equals(DiffMatchPatch.Operation.EQUAL)) {
                flag = 0;
            }
        }
        System.out.println(flag);
    }

It's the error shown:

java: variable flag might not have been initialized

Aucun commentaire:

Enregistrer un commentaire