带有while循环的选举程序中的错误

时间:2014-01-13 01:15:12

标签: java loops

我写了这个程序来计算每个人在选举中获得的总票数,并进入多个地区。当我尝试进入另一个区时,该程序只打印出从第一区收到的投票,而不是设置另一个投票。有什么问题,我该如何解决?

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); 
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您当前的循环已中断(因为您从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);

答案 1 :(得分:1)

您没有遍历轮询部分。

更改

    if (response.equals("Y")){

    while (response.equals("Y")){

并删除else语句。