due at midnight - program compiles but has logic error(s)

Posted by Leslie Laraia on Stack Overflow See other posts from Stack Overflow or by Leslie Laraia
Published on 2012-12-03T23:02:53Z Indexed on 2012/12/03 23:03 UTC
Read the original article Hit count: 104

Filed under:

not sure why this program isn't working. it compiles, but doesn't provide the expected output. the input file is basically just this:

Smith 80000

Jones 100000

Scott 75000

Washington 110000

Duffy 125000

Jacobs 67000

Here is the program:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 *
 * @author Leslie
 */
public class Election {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException {
        // TODO code application logic here

        File inputFile = new File("C:\\Users\\Leslie\\Desktop\\votes.txt");
        Scanner in = new Scanner(inputFile);
        int x = 0;
        String line = "";



        Scanner lineScanner = new Scanner(line);
        line = in.nextLine();

        while (in.hasNextLine())
        {
            line = in.nextLine();
            x++;
        }


        String[] senatorName = new String[x];
        int[] votenumber = new int[x];
        double[] votepercent = new double[x];


        System.out.printf("%44s", "Election Results for State Senator");
        System.out.println();
        System.out.printf("%-22s", "Candidate");     //Prints the column headings to the screen
        System.out.printf("%22s", "Votes Received");
        System.out.printf("%22s", "%of Total Votes");

        int i;

        for(i=0; i<x; i++)
        {
            while(in.hasNextLine())
           { 
             line = in.nextLine();
             String candidateName = lineScanner.next();
             String candidate = candidateName.trim();
             senatorName[i] = candidate;
             int votevalue = lineScanner.nextInt();
             votenumber[i] = votevalue;
           }
        }        

        votepercent = percentages(votenumber, x);


        for (i = 0; i < x; i++)
         {
            System.out.println();
            System.out.printf("%-22s", senatorName[i]);
            System.out.printf("%22d", votenumber[i]);
            System.out.printf("%22.2f", votepercent[i]);
            System.out.println();
         }               

    }

    public static double [] percentages(int[] votenumber, int z)
    { 
    double [] percentage = new double [z]; 

    double total = 0;
    for (double element : votenumber)
      {
        total = total + element;
      }
    for(int i=0; i < votenumber.length; i++)
      {
         int y = votenumber[i];
         percentage[i] = (y/total) * 100;
      }
    return percentage;

    }


}

© Stack Overflow or respective owner

Related posts about java