简体   繁体   中英

Why else statement is executing although if statement is true?

import java.util.Scanner;

class candidate {

    public String name;
    public int count;

    public candidate(String name) {
        super();
        this.name = name;
    }

}

public class DayScholar {
    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        candidate[] candidates = new candidate[3];
        candidates[0] = new candidate("vikas");
        candidates[1] = new candidate("ganesh");
        candidates[2] = new candidate("teja");

        System.out.print("No. of voters : ");
        int voters = in.nextInt();
        in.nextLine();
        for (int i = 0; i < voters; i++) {
            System.out.print("vote : ");
            String name = in.nextLine().toLowerCase();
            for (int j = 0; j < 3; j++) {

Here is the code, although if the statement is true else is also executing. How to check the condition

                if (name.equals(candidates[j].name)) {
                    candidates[j].count++;
                } else {            **//problem here**
                    System.out.println("N");
                    break;
                }


            }
        }

        int highest = 0;
        String winner = "";
        for (int i = 0; i < 3; i++) {
            if (candidates[i].count > highest) {
                highest = candidates[i].count;
                winner = candidates[i].name;
            } else if (candidates[i].count == highest) {
                winner += ("\n" + candidates[i].name);
            }
        }

        System.out.println(winner);
    }
}

Assuming the user enters a valid name, the following loop will increment the count field on the candidate with the matching name, and print N for the other 2 candidates .

for (int j = 0; j < 3; j++) {
    if (name.equals(candidates[j].name)) {
        candidates[j].count++;
    } else {
        System.out.println("N");
        break;
    }
}

To fix, you need the loop to just set the index of the matching candidate, then do the increment or printing after the loop:

int matchingIndex = -1; // -1 = not found
for (int j = 0; j < 3; j++) {
    if (name.equals(candidates[j].name)) {
        matchingIndex = j;
        break;
    }
}
if (matchingIndex == -1) {
    System.out.println("N");
} else {
    candidates[matchingIndex].count++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM