我正在创建一个方法来返回一个整数数组,其中包含用户“卡片”数组中所有卡片的总数以及 clown 和王牌的总数。它使用 for 循环并在包含按顺序排列的卡片的数组中查找卡片的值。如果该卡的面值大于 10,则应将面值 10 添加到总数中。
这是索引数组:
static String[] cardOrder = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
方法如下:
public static int[] total(ArrayList<String> cards){
int total = 0;
int aces = 0;
int jokers = 0;
for(int i = 0; i < cards.size(); i++){
System.out.println(i);
System.out.println(cards.size());
System.out.println("One of your cards is " + cards.get(i));
if(cards.get(i).equals("A")){
aces = aces + 1;
}else if(cards.get(i).equals("Joker")){
jokers = jokers + 1;
}else{
if(Arrays.asList(cardOrder).indexOf(cards.get(i)) <= 10){
total = total + Arrays.asList(cardOrder).indexOf(cards.get(i)) + 1;
}else{
total = total + 10;
}
}
System.out.println(total);
i++;
}
int[] intArray = {total, aces, jokers};
return intArray;
}
然而,奇怪的事情似乎正在发生。当我将 for 循环中的大于号更改为大于或等于时,我会遇到越界异常,但是当我不这样做时,只会计算卡片数组的第一个值。
抱歉,这看起来像是“修复我的代码”类型的线程。我认为这对于 Java 初学者社区来说非常有用,可以增强他们对 Java 方法中数组和数组列表的使用的理解。
最佳答案
你的 for 循环中有 i++ ,并且在 for 循环的末尾。删除底部的一个
关于Java - 卡的总值(value)。将数组的值与另一个数组中的位置进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26481835/