Java选票统计程序无论投票情况如何始终输出平局该如何解决?
问题原因
你代码的核心错误是字符串比较方式不符合Java语法规则:
- Java中
==用于String这类引用类型时,比较的是两个对象的内存地址是否相同,而非字符串内容是否相等 - 你通过
inputs.next()拿到的用户输入字符串vote,和代码里的常量字符串"A"、"B"是存放在不同内存地址的对象,所以所有vote == "A"、vote == "B"的判断结果永远为false,voteA和voteB始终都是初始值0,最终只会触发平局逻辑
修正方案
把投票计数的判断逻辑替换为equals方法比较字符串内容即可,推荐将常量字符串写在equals前,避免空指针异常:
//VOTE COUNT Scanner inputs = new Scanner(System.in); //getting total number of votes from user System.out.println("Enter the total number of votes in the election."); int voteNum = inputs.nextInt(); //defining the two different votes for the two candidates int voteA = 0; int voteB = 0; //collecting each vote one at a time from the user for (int i = 0; i < voteNum; i++) { System.out.println("Do you want to vote for candidate A or B? Enter A or B (Must be a capital letter)."); String vote = inputs.next(); // 修正字符串比较逻辑 if ("A".equals(vote)) { voteA = voteA + 1; } else if ("B".equals(vote)) { voteB = voteB + 1; } } //displaying the final result of the election if (voteA > voteB) { System.out.println("The election winner is candidate A!"); } else if (voteB > voteA) { System.out.println("The election winner is candidate B!"); } else { System.out.println("Candidate A and candidate B have tied!"); }
内容的提问来源于stack exchange,提问作者Tia Rojas
相关产品推荐
相关产品推荐

