gpt4 book ai didi

java - 如何修复Java中的 "looping and candidate voting"错误

转载 作者:行者123 更新时间:2023-12-02 04:13:07 27 4
gpt4 key购买 nike

我正在做一个投票系统,希望投票系统循环直到用户输入0,然后输出获胜的候选人

两个类

 package javaexamcode; 
import java.util.Scanner;

public class JavaExamCode {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Nominee mickey = new Nominee("Mickey Mouse");
Nominee donald = new Nominee("Donald Duck");
Nominee minnie = new Nominee("Minnie Mouse");
Nominee goofy = new Nominee("Goofy");

Scanner in = new Scanner(System.in);
while (true) {
System.out.println();
System.out.println("The presidential nominees are:");
System.out.println("1. Mickey Mouse");
System.out.println("2. Donald Duck");
System.out.println("3. Minnie Mouse");
System.out.println("4. Goofy");
System.out.print("What is your vote? ");

try{

int vote=in.nextInt();

if (vote==0){
break;
}else if (vote == 1){
mickey.increaseVote();
}else if (vote == 2){
donald.increaseVote();
}else if (vote == 3){
minnie.increaseVote();
}else if (vote ==4){
goofy.increaseVote();
}
else {
System.out.println("invalid");
}
break;
} catch (Exception e){
System.out.println("Invalid entry, try again");
continue;

}

}
Nominee[] candidates = new Nominee[]{mickey,donald,minnie,goofy};
Nominee president = winner(candidates);

System.out.println("The winner is " + president.toString() + " with " + president.totalVotes() + " votes.");
}

public static Nominee winner(Nominee[] all){
Nominee most = all[0];

for (int i = 1; i < all.length - 1; i++){
if (all[i].totalVotes() > most.totalVotes()){
most = all[i];
}else if (all[i].totalVotes() == most.totalVotes()){
String newName = all[i].toString() + " " + most.toString();
most = new Nominee(newName, (all[i].totalVotes() + most.totalVotes()));
}
}

return most;
}

}






package javaexamcode;
public class Nominee{
private String name;
private int votes;

public Nominee(String name){
this.name = name;
}

public Nominee (String name, int votes){
this.name = name;
this.votes = votes;
}

public void increaseVote(){
votes++;
}

public String toString(){
return name;
}

public int totalVotes(){
return votes;
}

}

当您输入 4 时也会出现错误,然后输出获胜者是 0 票的米奇和米妮。非常感谢您的帮助

网上查了一下,没找到太多

最佳答案

在你的方法中:

public static Nominee winner(Nominee[] all){
Nominee most = all[0];

for (int i = 1; i < all.length - 1; i++){
if (all[i].totalVotes() > most.totalVotes()){
most = all[i];
}else if (all[i].totalVotes() == most.totalVotes()){
String newName = all[i].toString() + " " + most.toString();
most = new Nominee(newName, (all[i].totalVotes() + most.totalVotes()));
}
}

return most;
}

你的 for 循环忽略了最后一个候选者(在本例中为#4)而不是循环条件i < all.length - 1你需要循环到i < all.length相反。

关于java - 如何修复Java中的 "looping and candidate voting"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56677259/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com