Monday, 27 August 2018

Array Does Not Print All Answers Correctly

Im making a main method that creates an array to keep track of some presidential candidates. The user inputs the number of candidates they want, and then inputs the candidates names they want in the election, then prints out the candidates with what position they were put in (1, 2, 3 not 0, 1, 2). Right now the method only prints out the 2nd and 3rd names, and will not print the 1st name.
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