public class RunElection
/**
*
*/
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please input the number of candidates you would like in this election.");
int numCandidates = scan.nextInt();
while (numCandidates <= 0) {
System.out.println("Please input a number that is greater than zero.");
numCandidates = scan.nextInt();
}
String[] candidates;
candidates = new String[numCandidates];
System.out.println("Please input the name of the candidates in the election.");
String newCandidate = scan.nextLine();
String newString = " ";
String finalString = " ";
for (int i = 0; i<candidates.length; i++) {
candidates[i] = newCandidate;
newCandidate = scan.nextLine();
}
for(int i = 0; i<candidates.length; i++) {
newString = "the candidates names are: " + " " + i + " ) " + candidates[i];
finalString = finalString+ newString;
}
System.out.println(finalString);
}
Here, the following for loop is the problem
for (int i = 0; i<candidates.length; i++) {
candidates[i] = newCandidate;
newCandidate = scan.nextLine();
}
What happens is, even though you feel like you are entering 5 candidates, you have actually stored 4 in the array. To resolve this, just interchange the lines as,
for (int i = 0; i<candidates.length; i++) {
newCandidate = scan.nextLine();
candidates[i] = newCandidate;
}
0 comments:
Post a Comment