【发布时间】:2021-08-06 09:21:30
【问题描述】:
我是 Java 新手,所以我正在做练习题。这个问题需要输出一个选举结果,但是无论用户输入投票给哪个候选人,它总是会输出打印语句声称它是平局。 (即使候选人 A 的选票多于候选人 B,反之亦然,它总是会说是平局)。
//VOTE COUNT
Scanner inputs = new Scanner(System.in);
//getting total number of votes from user
System.out.println("Enter the total number of votes in the election.");
int voteNum = inputs.nextInt();
//defining the two different votes for the two candidates
int voteA = 0;
int voteB = 0;
//collecting each vote one at a time from the user
for (int i = 0; i < voteNum; i++) {
System.out.println("Do you want to vote for candidate A or B? Enter A or B (Must be a capital letter).");
String vote = inputs.next();
//adding to candidate A and B's total votes depending on the vote
if (vote == "A") {
voteA = voteA + 1;
}
else if (vote == "B") {
voteB = voteB + 1;
}
}
//displaying the final result of the election
if (voteA > voteB) {
System.out.println("The election winner is candidate A!");
}
else if (voteB > voteA) {
System.out.println("The election winner is candidate B!");
}
else {
System.out.println("Candidate A and candidate B have tied!");
}
【问题讨论】:
-
我建议为您的变量添加
println()语句以查看发生了什么。阅读this article 了解更多调试技巧。 -
这能回答你的问题吗? How do I compare strings in Java?
标签: java if-statement variables input output