Java JUnit测试失败,不确定原因
我对编写代码相当陌生,我不是最好的,但我不明白为什么我的代码没有通过我设置的JUnit测试Java JUnit测试失败,不确定原因,java,junit,drjava,Java,Junit,Drjava,我对编写代码相当陌生,我不是最好的,但我不明白为什么我的代码没有通过我设置的JUnit测试 public class PA3Test { public static void main(String[] args) { } public static int countMajority(int count0, int count1, int count2) { int allVotes = (count0 + count1 + count2); int halfVotes
public class PA3Test {
public static void main(String[] args) {
}
public static int countMajority(int count0, int count1, int count2) {
int allVotes = (count0 + count1 + count2);
int halfVotes = (allVotes / 2);
int winner = 999;
if (count0 >= halfVotes) {
winner = 0;
} else {
winner = -1;
}
if (count1 >= halfVotes) {
winner = 1;
} else {
winner = -1;
}
return winner;
}
测试如下所示:
import junit.framework.TestCase;
public class PA3TestTest extends TestCase {
public static void testCountMajority() {
assertEquals("0th param should win:", 0,
PA3Test.countMajority(100, 50, 40));
assertEquals("1st param should win:", 1,
PA3Test.countMajority(50, 100, 40));
}
它应该返回0,但返回-1。感谢您的帮助。在您的第一次测试中,所有投票数=190
半数票=95
count0=100>95,获胜者=0
count1=50<95,获胜者=-1
试试下面,找出你做错了什么
public static int countMajority(int count0, int count1, int count2) {
int allVotes = (count0 + count1 + count2);
int halfVotes = (allVotes / 2);
int winner = -1;
if (count0 >= halfVotes) {
winner = 0;
}
else if (count1 >= halfVotes) {
winner = 1;
}
return winner;
}
不知道为什么当你有3次计数时,你的平均数是2。 但根据你的问题陈述,这应该可以解决问题
public static int countMajority(int count0, int count1, int count2) {
int allVotes = (count0 + count1 + count2);
int halfVotes = (allVotes / 2);
int winner = -1;
if (count0 >= halfVotes) {
winner = 0;
}
if (count1 >= halfVotes && count1 > count0) {
winner = 1;
}
return winner;
}
测试失败,因为您的函数应该返回0,但它返回-1,并且因为测试正在测试您的函数是否返回0,当你在IDE调试器中通过代码来查看它在做什么意想不到的事情时?我必须听起来愚蠢,但是为什么函数返回?1?非常仔细地考虑在行>代码>胜者=0之后发生了什么;<代码>执行。下一行要执行什么,以及之后的那一行?该死,这次行动如此接近,我希望他能根据我的提示自己弄明白。哦……好吧,我现在明白了问题所在,但现在我得到了一个错误,上面写着“else-without-if”。仍然有点困惑这比我想做的要简单得多,而且非常有意义,谢谢!