簡體   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