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

Java零基础求助:用ArrayList实现无预设候选人的选举程序

完善你的Java选举程序方案

Hey Laura, let's get this voting program working exactly how you need it! I see you're starting from scratch with Java, so I'll walk through each part clearly to help you understand what's going on.

First, let's sort out the issues in your current code:

  • You're using an ArrayList<Integer> to track candidate info, but we need to store names (strings) and their corresponding vote counts—so two separate ArrayLists will fit this need better.
  • The fixed for loop that runs 5 times doesn't match your requirement of stopping when the user enters -1. We'll switch to a while loop that runs until the termination signal is entered.
  • Your current code asks for a candidate name and then a vote count, but the requirement says users input individual votes one by one (just the candidate name each time, then -1 to end the process).

Here's the complete, working code with detailed explanations:

import java.util.ArrayList;
import java.util.Scanner;

public class Voting { 
    public static void main(String[] args) { 
        Scanner input = new Scanner(System.in); 
        
        // 存储候选人名字的列表
        ArrayList<String> candidates = new ArrayList<>();
        // 存储对应候选人的票数,索引和candidates列表一一对应
        ArrayList<Integer> voteCounts = new ArrayList<>();

        System.out.println("Enter candidate names one by one (enter -1 to stop voting):");
        
        // 持续接收选票输入,直到用户输入-1
        while (true) {
            System.out.print("Enter vote: ");
            String vote = input.nextLine().trim(); // 读取整行输入,去除前后空格
            
            // 检查是否触发终止条件
            if (vote.equals("-1")) {
                break;
            }
            
            // 检查当前候选人是否已经在列表中
            int candidateIndex = candidates.indexOf(vote);
            if (candidateIndex != -1) {
                // 候选人已存在,票数加1
                voteCounts.set(candidateIndex, voteCounts.get(candidateIndex) + 1);
            } else {
                // 候选人不存在,添加到列表并初始化票数为1
                candidates.add(vote);
                voteCounts.add(1);
            }
        }
        
        // 处理没有任何选票的边界情况
        if (candidates.isEmpty()) {
            System.out.println("No votes were cast.");
            input.close();
            return;
        }
        
        // 找出得票最多的获胜者
        int maxVotes = 0;
        String winner = "";
        for (int i = 0; i < voteCounts.size(); i++) {
            int currentVotes = voteCounts.get(i);
            if (currentVotes > maxVotes) {
                maxVotes = currentVotes;
                winner = candidates.get(i);
            }
        }
        
        // 输出所有候选人的得票情况
        System.out.println("\nVote Results:");
        for (int i = 0; i < candidates.size(); i++) {
            System.out.println(candidates.get(i) + ": " + voteCounts.get(i) + " votes");
        }
        
        // 输出最终获胜者
        System.out.println("\nThe winner is " + winner + " with " + maxVotes + " votes!");
        
        input.close();
    } 
}

Let's break down the key parts to help you follow along:

  • Data Structures: We use two ArrayLists to keep track of candidate names and their vote counts. The index position of each candidate in the names list directly matches their vote count in the counts list.
  • Input Handling: The while(true) loop runs indefinitely until the user enters -1. Using input.nextLine() lets us handle names with spaces (though your requirement specifies single votes, this adds flexibility).
  • Vote Counting: For each vote, we check if the candidate exists using indexOf(). If they do, we increment their vote count; if not, we add them to both lists with an initial vote count of 1.
  • Finding the Winner: We loop through the vote counts to find the highest number, then map that value back to the corresponding candidate name.
  • Edge Case Handling: We add a check for empty votes to avoid runtime errors if no one casts a vote.

You can run this code, test it by entering candidate names one by one, then type -1 to see the final results!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:39:36