1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

New to JS - help!

Discussion in 'Scripting & Programming' started by rwilmot, Jun 17, 2009.

  1. rwilmot

    rwilmot Nibble Poster

    62
    0
    28
    Hi Folks,

    Newbie here so please be patient!

    I have the following code below. Basically I need to be able to enter the number of candidates into a window prompt, then give a name to each of those candidates and then enter a vote score for each candidate and then work out who won!! I have posted the code that I have most recently been working on and I'm pretty sure things are in the wrong place.. :rolleyes: :oops:

    Thanks in advance

    <SCRIPT

    language="JavaScript"
    type="text/javascript">

    /* Program to summarise the results of the election for Secretary.
    There were 5 candidates.
    */
    // Declare variables
    var totalMembership, numberOfCandidates, totalVote;
    var candidateNameArray;
    var candidateVoteArray;

    // For each candidate the number of votes cast is entered
    // and the running total of votes cast so far is calculated
    numberOfCandidates = parseFloat(window.prompt('Enter the number of Candidates',''));
    numberOfCandidates = candidateNameArray.length;
    for (var candidateName = 0; candidateName < numberOfCandidates;
    candidateName = candidateName + 1)
    {
    candidateNameArray[candidateName] = window.prompt('Please enter the Candidates name','');
    }

    totalVote = 0;
    //for (var count = 0; count < numberOfCandidates; count = count + 1)
    {
    candidateVoteArray[count] = candidateVoteArray[count] +
    parseFloat(window.prompt
    ('Please enter the votes cast for candidate ' + (count + 1)));
    totalVote = totalVote + candidateVoteArray[count];
    }
    // The total votes cast is written out

    document.write('Total votes cast: ' + totalVote + '<BR>');

    /*For each candidate, their total vote and their percentage share of the vote is output*/
    for (var count = 0; count < numberOfCandidates; count = count + 1)
    {
    var percentageVote;
    percentageVote = (candidateVoteArray[count] / totalVote) * 100;
    percentageVote = Math.round(percentageVote * 100) / 100;
    document.write(candidateNameArray[count] +
    '........votes: ' + candidateVoteArray[count] +
    '........% of total vote: ' + percentageVote + '<BR>');
    }
    /* The winning candidate is declared by determining the array index with the largest vote
    (assumes that there is an overall winner and no possibility of a tied ballot) */
    var maxIndex;
    maxIndex = 0;
    for (var count = 0; count < candidateNameArray.length; count = count + 1)
    if (candidateVoteArray[count] > candidateVoteArray[maxIndex])
    {
    maxIndex = count;
    }
    document.write('Winner is Candidate ' + (maxIndex+1) + ' with '
    + candidateVoteArray[maxIndex] + ' votes');

    </SCRIPT>
     
    Certifications: Village Idiot Award
    WIP: working towards everything..
  2. zimbo
    Honorary Member

    zimbo Petabyte Poster

    5,215
    98
    181
    ok i did 3 yrs of java but never jscript.. but im trying to help! Ok there are a few glitches (i think they are unless you can do it in jscript!)

    Bascially lets start over with pseudo code:

    If you know you will only have 5 candidates do you really need to ask how many they want?

    So you create a multidimensional array to hold 5 and the other stuff you want (average votes etc)

    Now all this can be done in one for loop you ask for candidate 1 to enter their name and their votes, loop increments same for 2... and so on until you reach <5

    you then do a nested for loop one for the candidate and the second to go through the votes to find out who has the max - in this loop you can have a variable with an if statement to keep track of the highest person and their votes.

    In the end another loop to do averages and print out..

    ps it might all by junk i written but if it doesnt help i could look back at your code!

    pps: why parsefloat and not parseint? :

    numberOfCandidates = parseFloat(window.prompt('Enter the number of Candidates',''));
     
    Certifications: B.Sc, MCDST & MCSA
    WIP: M.Sc - Computer Forensics
  3. rwilmot

    rwilmot Nibble Poster

    62
    0
    28
    Hey Zimbo,

    Thanks for the quick reply. Some of what you said made sense but most of it didn't. The code that I posted is what I have to work with, I am supposed to make it work using what is there.

    Would you (or anyone else?????) be able to make any suggestions using the code as it is??

    Thanks,

    Richie
     
    Certifications: Village Idiot Award
    WIP: working towards everything..
  4. LordMoolyBap

    LordMoolyBap Nibble Poster

    95
    0
    28
    Hi,

    You may want to check out some tutorials like www.w3schools.com. Anyway, I am not an expert in Javascript but my friend who sits next to me is.

    Code:
    <html>
    <head>
      <SCRIPT type="text/javascript">	
      
      var electionManager = {}
      
      electionManager.run = function() {
        /* Program to summarise the results of the election for Secretary.	
        There were 5 candidates. 
        */ 
        // Declare variables
        var numberOfCandidates;
        var index;
        var candidates = [];
        var candidateName;
        var totalVotes = 0;
        var highestVote = 0;
        var highestVoteIndex = 0;
        
        // For each candidate the number of votes cast is entered 
        // and the running total of votes cast so far is calculated
        numberOfCandidates = parseInt(window.prompt('Enter the number of Candidates',''));
        
        candidates = [];
        
        for (index = 0; index < numberOfCandidates; index++) {
          candidateName = window.prompt('Please enter the Candidates name','');  
          candidates[index] = { name: candidateName };
        }
        
        for (index in candidates) {
          candidates[index].votes = parseInt(window.prompt('Please enter the votes cast for candidate ' + candidates[index].name));
          totalVotes += candidates[index].votes;  
          if (candidates[index].votes > highestVote) {
            highestVoteIndex = index;
          }
        }
        
        document.write('<p>Total votes cast: ' + totalVotes + '</p>');
        
        /*For each candidate, their total vote and their percentage share of the vote is output*/
        for (index in candidates)
        {  
          document.write('<p>' + candidates[index].name +
          '........votes: ' + candidates[index].votes +
          '........% of total vote: ' + Math.round((candidates[index].votes / totalVotes) * 100) + '</p>');
        }
        /* The winning candidate is declared by determining the array index with the largest vote 
        (assumes that there is an overall winner and no possibility of a tied ballot) */	
        document.write('Winner is Candidate ' + candidates[highestVoteIndex].name + ' with ' 
        + candidates[highestVoteIndex].votes + ' votes');
      };
      
      </SCRIPT>
    </head>
    <body>
      <SCRIPT type="text/javascript">	
        electionManager.run();
      </SCRIPT>
    </body>
    </html>
    
    That will do the trick. Use a javascript debugger like FireBug or IE8s built in one. Also check out this book
     
    Certifications: HND (Comp) MBCS
    WIP: Msc Intelligent Systems
  5. LordMoolyBap

    LordMoolyBap Nibble Poster

    95
    0
    28
    just one other thing. I noticed you were doing some sort of crazy way to get to 2 decimal places at the end there.
    I think a better way would be to use the toPrecision() method

    Hope that helps,

    Dom
     
    Certifications: HND (Comp) MBCS
    WIP: Msc Intelligent Systems
  6. rwilmot

    rwilmot Nibble Poster

    62
    0
    28
    Ya see, this is why I love everyone here.

    Great job guys, thanks!
     
    Certifications: Village Idiot Award
    WIP: working towards everything..

Share This Page

Loading...