我最近开设了一门课程,目前我们学习的主要语言是Java。
我的任务是创建一个程序,允许人们对两个候选人进行投票 - 然后程序计算投票次数,并且取决于人们如何投票取决于显示的内容。
这是我现在关注的部分:
public String printResults(){
if(candidate1Votes == 0 && candidate2Votes == 0)
{
System.out.println ("No votes cast, results cannot be displayed.");
return "No votes cast, results cannot be displayed.";
}
else if(this.completed == false)
{
System.out.println ("Voting has not finished");
return "Voting has not finished";
}
else if(this.completed == true)
{
System.out.println ("Voting has finished, no more votes will be allowed.");
return "Voting has finished, no more votes will be allowed";
}
{
double totalVotes = this.candidate1Votes + this.candidate2Votes;
double cand1Share = (double) this.candidate1Votes/totalVotes*100;
double cand2Share = (double) this.candidate2Votes/totalVotes*100;
System.out.format(candidate1 + " received %3.1f percent of the votes\n", cand1Share);
System.out.format(candidate2 + " received %3.1f percent of the votes\n", cand2Share);
return "v";
}
}
最初我在这个方法中使用了void,但是我们的任务的一部分是将其更改为字符串值。这就是我在努力的地方 - 一旦我完成了真实,它仍然允许我投票。我知道这段代码不完整但我无法完成,因为我不确定该怎么做!这些是问题的下一部分。
我是新手(这是我的第一年)并且已经设法在我的书中做得很好,但是对于下一期的任何帮助将不胜感激!
答案 0 :(得分:0)
您的第一个代码是不必要的复杂,这使得难以阅读/增强。它可以轻松简化,例如
public String printResults(){
if(candidate1Votes == 0 && candidate2Votes == 0) {
System.out.println ("No votes cast, results cannot be displayed.");
return "No votes cast, results cannot be displayed.";
} // you returned ... NO need for ELSE!
if(this.completed == false) {
System.out.println ("Voting has not finished");
return "Voting has not finished";
}
// it is very clear here that completed must be true!
double totalVotes = this.candidate1Votes + this.candidate2Votes;
double cand1Share = (double) this.candidate1Votes/totalVotes*100;
double cand2Share = (double) this.candidate2Votes/totalVotes*100;
System.out.format(candidate1 + " received %3.1f percent of the votes\n", cand1Share);
System.out.format(candidate2 + " received %3.1f percent of the votes\n", cand2Share);
return "v";
}
可能更容易阅读的代码就是您需要的所有内容!
答案 1 :(得分:0)
查看代码永远不会到达最后一个块,因为你没有投票或者你有投票,在这种情况下,完成将是真或假,因此将始终到达else if
和他们都返回一个字符串。所以我想知道为什么你可以投票。
您也可以在调用printResults和setCompleted的位置发布代码,以查看问题所在。
有关改进代码的更多提示:
if (this.completed == true)
和else if (this.completed == false)
有点多余,可以写成:if (this.completed)
和if (!this.completed)
。你也可以写
if (this.completed) {
...
} else {
....
}
因为如果完成不是真的那么它只能是假的。
如果您想要更改某些内容,您可以执行以下操作,而不是两次编写每个字符串并且必须编辑两次:
String msg = "Voting has not finished"
System.out.println(msg);
return msg;