本教程讲解如何优化投票统计程序,使其仅在某一名次(如第二、第三)实际获得票数时才输出对应信息,跳过票数为零的名次,提升结果展示的准确性与可读性。
在实现投票结果排序与展示时,一个常见但易被忽略的问题是:即使某一名次(如“Third Place”)得票数为 0,程序仍会打印该标题并留空,造成误导或冗余输出。根本原因在于——标题打印逻辑与数据查找逻辑未解耦,且缺乏对票数有效性的前置判断。
解决思路非常清

以下是重构后的推荐写法(基于您原有的数组结构 Array[] 存储票数,stringArray[] 存储候选人姓名):
// ✅ Winner (always shown, assuming at least one vote exists)
System.out.print("Winner: ");
for (int i = 0; i < Array.length; i++) {
if (Array[i] != 0 && Array[i] == firstScore) {
System.out.print(stringArray[i] + " ");
}
}
System.out.println(); // 使用 println 换行更简洁
// ✅ Second Place — 仅当 secondScore > 0 时才显示
if (secondScore > 0) {
System.out.print("Second: ");
for (int i = 0; i < Array.length; i++) {
if (Array[i] != 0 && Array[i] == secondScore) {
System.out.print(stringArray[i] + " ");
}
}
System.out.println();
}
// ✅ Third Place — 同理,严格校验 thirdScore > 0
if (thirdScore > 0) {
System.out.print("Third: ");
for (int i = 0; i < Array.length; i++) {
if (Array[i] != 0 && Array[i] == thirdScore) {
System.out.print(stringArray[i] + " ");
}
}
System.out.println();
}⚠️ 关键注意事项:
通过这一改进,输出将从冗余的:
Third: Second: Joey Winner: Miles
变为干净专业的:
Second: Joey Winner: Miles
真正实现“所见即所得”,让投票结果摘要既准确又简洁。