gpt4 book ai didi

java - 使用 while 循环的选举程序中的错误

转载 作者:行者123 更新时间:2023-12-02 06:20:17 24 4
gpt4 key购买 nike

我编写这个程序是为了计算每个人在选举中获得的总票数,并进入多个选区。当我尝试进入另一个选区时,程序只会打印从第一个选区收到的选票,而不是设置另一个民意调查。这是什么问题以及如何修复它?

import java.util.Scanner;

public class Election{
public static void main (String[] args){
int votesForPolly = 0; // number of votes for Polly in each precinct
int votesForErnest = 0; // number of votes for Ernest in each precinct
int totalPolly = 0; // running total of votes for Polly
int totalErnest = 0; // running total of votes for Ernest
String response = ""; // answer (y or n) to the "more precincts" question

Scanner scan = new Scanner(System.in);

System.out.println ();
System.out.println ("Election Day Vote Counting Program");
System.out.println ();
// Initializations

// Loop to "process" the votes in each precinct
{
System.out.println ("Enter Votes? Enter Y or N");
response=scan.next().toUpperCase();
if (response.equals("Y")){
response="Yes";
System.out.println ("Enter votes for Polly:");
votesForPolly=scan.nextInt();
totalPolly=totalPolly+ votesForPolly;
System.out.println ("Enter votes for Ernest:");
votesForErnest=scan.nextInt();
totalErnest=totalErnest+ votesForErnest;
System.out.println ("Enter another District? Enter Y or N");
response=scan.next().toUpperCase();
}else{

int count = 0;

while (count == 1){

// Print out the results

}
}
System.out.println ("Total votes for Polly is: " + totalPolly);
System.out.println ("Total votes for Ernest is: " + totalErnest);
}
}
}

最佳答案

您当前的循环已损坏(因为您从 count = 0 开始,因此未输入 while (count == 1),我将重写如下

final String msg = "Enter Votes for District %d?"
+ " Enter Y to continue, N to stop.\n";
// Loop to "process" the votes in each precinct
for (int i = 1;; i++) {
System.out.printf(msg, i);
response = scan.next().toUpperCase();
if (response.startsWith("N")) {
break;
}
System.out.println("Enter votes for Polly: ");
votesForPolly = scan.nextInt();
totalPolly += votesForPolly;
System.out.println("Enter votes for Ernest: ");
votesForErnest = scan.nextInt();
totalErnest += votesForErnest;
}
System.out.printf("Total votes for Polly is: %d\n"
+ totalPolly);
System.out.printf("Total votes for Ernest is: %d\n"
+ totalErnest);

关于java - 使用 while 循环的选举程序中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21082509/

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