title: Vote Count Tallying
body: <p>I was presented with the problem of creating a java program that tallies the votes of each individual candidate. We are supposed to use arrays; however, we were just taught them, and I am not quite following how to solve this.</p>
  
  <p>The file we are supposed to read from is this:</p>
  
  <p>4    7</p>
  
  <p>2    10</p>
  
  <p>3    2</p>
  
  <p>3    4</p>
  
  <p>4    5</p>
  
  <p>5    6</p>
  
  <p>7    9</p>
  
  <p>0    12</p>
  
  <p>1    2</p>
  
  <p>3    45</p>
  
  <p>6    9</p>
  
  <p>55   19</p>
  
  <p>-4   11</p>
  
  <p>4    4</p>
  
  <p>3    -21</p>
  
  <p>The left column is the candidate number, and the right is the number of votes. </p>
  
  <p>The first column can only be a whole number from 1-10. The second can be any positive value.
  In the end, the program is supposed to add together the total votes cast for each candidate. </p>
  
  <p>I think we need an array that goes something like: <code>int[] cands = new int[10]</code> It specifies the candidate number. However, I do not understand how to organize the values. Sorry if this seems jumbled..I am not sure how to explain this as I am slightly confused. Do I need more than just one array?</p>
  
  <p>Here is a snippet of the directions: </p>
  
  <blockquote>
    <p>Each line in this file contains two numbers: the first is the candidate identifier (1-10) and the second is the number of votes that candidate received.   Your program will tally the number of votes per candidate using an array where each array entry represents a candidate.    Notice that each array entry acts as a accumulator of votes for that candidate.   </p>
  </blockquote>
  
  <p>Edit: This is what I have so far..</p>
  
  <pre><code>public static void main(String[] args) throws IOException {
  
  File file = new File("Tally.txt");
  Scanner input = new Scanner(file);
  int[] cands = new int[10];
  int cnt = 0;
  
  while (input.hasNextLine()) {
      int cand = input.nextInt() - 1;
      int vote = input.nextInt();
  
      if ((cand &gt;= 0 &amp;&amp; cand &lt; cands.length) &amp;&amp; vote &gt; 0) {
      cands[cand] += vote;
      }
  }
  
  System.out.println("Canidate:  \t  Votes:");
  for (int index = 1; index &lt; cands.length + 1; index++) {
      if (cnt &lt; cands.length) {
      System.out.println("\t " + index + "\t\t" + cands[cnt]);
      cnt++;
      }
  }
  input.close();
  }
  </code></pre>
  
  <p>}</p>
  
  <p>However, once it reaches a negative value or a value higher than 10 in the file it throws all kinds of errors (such as java.util.NoSuchElementException). How can I avoid this?</p>