简体   繁体   English

为什么我的方法只返回存在于我的 ArrayList 中的重复项之一?

[英]Why is my method only returning one of the duplicates that exist in my ArrayList?

I'm creating a poker game in Java, as of right now I am trying to find duplicate ranks in an ArrayList and printing them.我正在用 Java 创建一个扑克游戏,现在我正在尝试在 ArrayList 中找到重复的排名并打印它们。 My ArrayList (cards) contains ["3c", "3s", "Ad", "6h", "7h", "7s"].我的 ArrayList(卡片)包含 ["3c", "3s", "Ad", "6h", "7h", "7s"]。 When I use the method I've created当我使用我创建的方法时

String firstChar;

public void twoPair() {
        for(String t : cards) {
            char rank_index = t.charAt(0);
            firstChar = String.valueOf(rank_index);
        }
        for (String i : cards) {
            if (i.startsWith(firstChar)) System.out.println(i);
        }
    }

I get an output of:我得到一个输出:

 7h
 7s

and similarily, If I add another 7 card (like 7c), I get all three of the 7 cards,类似地,如果我再添加 7 张牌(如 7c),我会得到 7 张牌中的所有三张,

7h
7s
7c

but not the duplicates of rank 3 cards ("3c" and "3s").但不是 3 级卡的副本(“3c”和“3s”)。 Full code at https://github.com/aepries/A8-Poker完整代码在https://github.com/aepries/A8-Poker

You need a nested loop, in its original form, it would just check for last entry in array list and that is 7 and hence you see all the elements whose starting character is 7.您需要一个原始形式的嵌套循环,它只会检查数组列表中的最后一个条目,即 7,因此您会看到所有起始字符为 7 的元素。

You should change the code to:您应该将代码更改为:

for(String t : cards) {
    char rank_index = t.charAt(0);//no need to convert to string
    for (String i : cards) {
        if (!i.equals(t) && i.charAt(0) == rank_index) 
            System.out.println(i);
    }
}

The first loop assigns your variable to 7s in which your n-th value therefore it only picks the value that is related to 7 .第一个循环将您的变量分配给7s ,其中您n-th值因此它只选择与7相关的值。 My solution would look like a point system in which we just need to add +1 in each character, any value that has less than 1 will not be outputed.我的解决方案看起来像一个点系统,其中我们只需要在每个字符中添加+1 ,任何小于 1 的值都不会输出。

public static void main(String[] args) {

        List<String> cards = new ArrayList<>();
        cards.add("3c");
        cards.add("3s");
        cards.add("Ad");
        cards.add("6h");
        cards.add("7h");
        cards.add("7s");
        cards.add("7c");

        Map<Character, Integer> list = new HashMap<>();
        for (String card : cards) {
            char c = card.charAt(0);
            if (!list.containsKey(c)) {
                list.put(c, 0);
            } else {
                list.put(c, list.get(c) + 1);
            }
        }

        for (String card : cards) {
            char c = card.charAt(0);
            if(list.get(c) > 0){
                System.out.println(card);
            }
        }
    }

The time complexity is only O(n*2).时间复杂度仅为O(n*2).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM