繁体   English   中英

JUnit 测试失败,不知道为什么

[英]JUnit Test failing and not sure why

我对编写代码很陌生,我不是最好的,但我不明白为什么我的代码没有通过我设置的 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 = (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
计数 1 = 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;
}

暂无
暂无

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

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