Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Ten candidates, designated 0 to 9, are competing in a preliminary election for m

ID: 3544845 • Letter: T

Question

Ten candidates, designated 0 to 9, are competing in a preliminary election for mayor. Write a program that counts the votes for each candidate. The input to your program is a list of numbers in the range 0-9 such that a value of i signifies a vote for candidate i. Terminate the data with a flag. Use an array to keep a tally of the votes. Do not use ten different variables. Discard all invalid votes. Output from your program should be 10 pairs (one pair per line) of the form:

(candidate number, number of votes)


Typical input might be:

113334126790231454478903453123412311123-999

Explanation / Answer

package array;


import java.util.Scanner;


public class ElectionSample {


public static void main(String[] args) {

int[] votes = new int[10];

for(int i=0;i<10;i++){

votes[i]=0;

}

Scanner sc = new Scanner(System.in);

String input = sc.nextLine();

int num;

for(int i=0;i<input.length();i++){

if(!Character.isDigit(input.charAt(i))){

break;

}

else if(Character.isDigit(input.charAt(i))){

num = Integer.parseInt(input.substring(i, i+1));

if(num<0 || num>=10){

break;

}

votes[num]=votes[num]+1;

}

}

for(int i=0;i<10;i++){

System.out.println(i + "," + votes[i]);

}

sc.close();

}


}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote