为什么else语句正在执行,尽管if语句为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++) {

这是代码,尽管如果语句为true,else也在执行。如何检查条件

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);
}
}

假设用户输入了一个有效的名称,下面的循环将在具有匹配名称的候选者上增加count字段,并为其他2个候选者打印N

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

要修复此问题,您需要循环只设置匹配候选者的索引,然后在循环后执行增量或打印

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++;
}

最新更新