[英]Java CARD Class compare method
int[] value = new int[5];
boolean result = true;
for(int i = 0; i < 5; i++) {
value[i] = cards[i].getValue();
}
for(int i = 0; i < 5; i++) {
for(int j = i;j < 5; j++) {
if(value[i] == value[j + 1]) {
result = false;
}
}
}
return result;
This code is essentially going to compare the values each card object has, and if two cards in the array have the same value return true. 此代码本质上将比较每个卡对象具有的值,如果数组中的两张卡具有相同的值,则返回true。 We have 5 cards in each hand and that is why the array length is 5. The
getValue
method returns an integer which is essentially the value of the card. 我们每手有5张卡片,这就是数组长度为5的原因
getValue
方法返回一个整数,该整数本质上是卡片的值。 I don't seem to know what I'm doing wrong to be getting errors on my method. 我似乎不知道自己在做错什么,因为我的方法出错了。
Your array access is incorrect when you use j + 1
, that will be out of bounds when j
is four (at the end of the length for value
). 当您使用
j + 1
,您的数组访问不正确,这将在j
为4时超出范围(在value
的长度的末尾)。 And, I would prefer to use value.length
instead of hardcoding. 而且,我宁愿使用
value.length
而不是硬编码。 Something like 就像是
for (int i = 0; i < value.length - 1; i++) {
for (int j = i + 1; j < value.length; j++) {
if (value[i] == value[j]) {
result = false;
}
}
}
Additionally, as pointed out by Tom, in the comments; 此外,正如汤姆(Tom)指出的那样,在评论中; it is pointless to continue iteration when the
result
becomes false
. 当
result
false
时继续迭代是没有意义的。 You could simply return when it becomes false
and avoid the result
variable entirely. 当它变为
false
时,您可以简单地返回,并完全避免使用result
变量。 Like, 喜欢,
for (int i = 0; i < value.length - 1; i++) {
for (int j = i + 1; j < value.length; j++) {
if (value[i] == value[j]) {
return false;
}
}
}
return true;
Another option, in Java 8+, would be something like 在Java 8+中, 另一种选择是
return IntStream.of(value).allMatch(x -> value[0] == x);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.