简体   繁体   English

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

[英]JUnit Test failing and not sure why

I'm pretty new to writing code and I am not the best, but I don't understand why my code isn't passing one of the JUnit tests I have set up.我对编写代码很陌生,我不是最好的,但我不明白为什么我的代码没有通过我设置的 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;

}

The test looks like this:测试看起来像这样:

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));
}   

It is supposed to be returning 0 but it is returning -1.它应该返回 0 但它返回 -1。 Any help is appreciated.任何帮助表示赞赏。

In your first test,在你的第一次测试中,
allVotes=190所有投票数=190
halfVotes=95半票数=95
count0 = 100 > 95, winner = 0 count0 = 100 > 95,获胜者 = 0
count1 = 50 < 95, winner = -1计数 1 = 50 < 95,获胜者 = -1


Try below and find out what you are doing wrong. 试试下面的方法,找出你做错了什么。

 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; }

Not sure why you are averaging it by 2 when you are having 3 counts.不知道为什么当你有 3 个计数时,你把它平均为 2。 But based on your problem statement this should do the trick.但是根据您的问题陈述,这应该可以解决问题。

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