简体   繁体   中英

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. My ArrayList (cards) contains ["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,

7h
7s
7c

but not the duplicates of rank 3 cards ("3c" and "3s"). Full code at 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.

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 . 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.

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).

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.

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