You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

名字投票统计代码调试求助:统计重复名次数并输出胜者

Fixing the Popularity Contest Vote Counter

Let's get your vote counting code working properly! First, let's break down the issues in your original snippet, then build a solution that meets your requirements.

Issues in the Original Code

  • Type mismatch: You tried to assign both a string and an integer to largest_count—Java won't allow that. We need separate variables for the winner's name and their vote count.
  • Incorrect sorting: Java doesn't have a sorted() method that returns an integer for a List. To sort a List, use Collections.sort(), which modifies the list in place.
  • Invalid List access: You treated the List like an array (using n[i] and name_list.length). For Lists, use get(i) to access elements and size() to get the length.
  • Un-declared variables: Variables like i and name need explicit type declarations in Java.
  • Incomplete logic: Your code didn't handle the last group of names in the sorted list, and never updated the winner tracking variables.

Working Solution 1: Using HashMap (Efficient & Clean)

This approach counts votes without sorting, which is more efficient for larger datasets:

import java.util.List;
import java.util.HashMap;
import java.util.Map;

public class VoteCounter {
    static void popularity_contest(List<String> name_list) {
        // Map to store each name and its vote count
        Map<String, Integer> voteCounts = new HashMap<>();
        
        // Count votes
        for (String name : name_list) {
            voteCounts.put(name, voteCounts.getOrDefault(name, 0) + 1);
        }
        
        // Track the winner
        String winner = "";
        int maxVotes = 0;
        
        // Print each name's vote count and find the winner
        for (Map.Entry<String, Integer> entry : voteCounts.entrySet()) {
            String name = entry.getKey();
            int count = entry.getValue();
            System.out.printf("(%s) got (%d) votes.%n", name, count);
            
            // Update winner if current name has more votes
            if (count > maxVotes) {
                maxVotes = count;
                winner = name;
            }
        }
        
        // Print the final winner
        System.out.println("\nThe winner is: " + winner);
    }

    // Test with your sample data
    public static void main(String[] args) {
        List<String> names = List.of("John", "Mary", "Joe", "John", "John", "John", "Mary", "Mary", "Steve");
        popularity_contest(names);
    }
}

Working Solution 2: Sorted List Approach (Matching Your Original Idea)

If you prefer to use sorting like your initial attempt, here's a fixed version:

import java.util.List;
import java.util.Collections;
import java.util.ArrayList;

public class VoteCounterSorted {
    static void popularity_contest(List<String> name_list) {
        // Make a copy of the list to avoid modifying the original
        List<String> sortedNames = new ArrayList<>(name_list);
        Collections.sort(sortedNames);
        
        String winner = "";
        int maxVotes = 0;
        int currentCount = 1;
        int listSize = sortedNames.size();
        
        // Handle edge case: empty list
        if (listSize == 0) {
            System.out.println("No votes to count!");
            return;
        }
        
        String currentName = sortedNames.get(0);
        
        // Iterate through sorted list to count votes
        for (int i = 1; i < listSize; i++) {
            String nextName = sortedNames.get(i);
            if (nextName.equals(currentName)) {
                currentCount++;
            } else {
                // Print current name's count
                System.out.printf("(%s) got (%d) votes.%n", currentName, currentCount);
                
                // Update winner if needed
                if (currentCount > maxVotes) {
                    maxVotes = currentCount;
                    winner = currentName;
                }
                
                // Reset for next name
                currentName = nextName;
                currentCount = 1;
            }
        }
        
        // Don't forget to print the last name's count
        System.out.printf("(%s) got (%d) votes.%n", currentName, currentCount);
        if (currentCount > maxVotes) {
            maxVotes = currentCount;
            winner = currentName;
        }
        
        // Print winner
        System.out.println("\nThe winner is: " + winner);
    }

    // Test with sample data
    public static void main(String[] args) {
        List<String> names = List.of("John", "Mary", "Joe", "John", "John", "John", "Mary", "Mary", "Steve");
        popularity_contest(names);
    }
}

Sample Output

Both solutions will produce this output for your test list:

(John) got (4) votes.
(Mary) got (3) votes.
(Joe) got (1) votes.
(Steve) got (1) votes.

The winner is: John

内容的提问来源于stack exchange,提问作者jwacki24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:51:48