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.
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. Any help is appreciated.
In your first test,
allVotes=190
halfVotes=95
count0 = 100 > 95, winner = 0
count1 = 50 < 95,
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. 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.