我是初学者的java课程。我已经有了这个Yahtzee计划已经有好几个星期了,我仍然无法理解这一点。
从checkTwopairs()
获取积分时遇到问题。 checkTwopairs()
可以查看是否有两对。但是我有一个难以解决的问题。有什么好方法吗?
public int checknumber(int nr) {
int sum = 0;
for (Dice d : diceList) {
if (d.getValue() == nr ){
sum++;
}
}
return sum;
}
public void checkTwopairs() {
for (int i = 1; i <= 6; i++) {
int a = checknumber(i);
if (a == 2) {
if (twopair == true && a == 2) {
} else {
twopair = true;
}
}
}
twopair = false;
}
答案 0 :(得分:0)
这是一种替代这两种方法的单方法解决方案:
public void checkTwoPairs() {
int numPairs = 0;
//two pairs haven't been found yet
boolean twoPair = false;
//for each possible number
for(int i = 1; i <= 6; i++) {
int sum = 0;
//for each dice object
for(Dice d : diceList) {
//if i is the dice value
if(d.getValue() == i) {
//increment the number of matches
sum++;
}
}
//sum % 2 - gives you the number of pairs for that number checked
numPairs += (sum%2);
//if you have 2 pairs
if(numPairs == 2) {
//set twoPair = true ... and break out of the loop
twoPair = true;
break;
}
//if you don't have 2 pairs yet, go back through the loop
}
}
答案 1 :(得分:0)
我猜你正在寻找2对,这意味着你得到{5,5,2,2,1}的骰子你有2对 - 一对5&#39; s和一对2。
我认为你可能正在寻找这样的东西来修改你的代码:
public void checkTwopairs() {
boolean firstPair = false; // New local variable.
for (int i = 1; i <= 6; i++) {
int a = checknumber(i);
if (a == 2) {
//if (twopair == true && a == 2) <--- This second clause is unnecessary as we can only get here if a == 2
if (firstPair == true) {
twopair = true;
return; //This returns the method, so twopair cannot be set to false if two pairs are found
} else {
firstPair = true;
}
}
}
//Checked all dice, less than two pairs were found.
twopair = false;
}