繁体   English   中英

尽管 if 语句为真,为什么 else 语句正在执行?

[英]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++) {

这是代码,尽管如果语句为真,其他也正在执行。 如何检查条件

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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