Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 02-11-2011, 08:40 PM   PM User | #1
BuhRock
New Coder

 
Join Date: Feb 2010
Posts: 24
Thanks: 4
Thanked 0 Times in 0 Posts
BuhRock is an unknown quantity at this point
Dividing elements in two diferrent arrays

I am using an array to store 5 test scores. Then I have another array for the total possible score the test could have. I just need to find out what percent the grade is out of the total possible score.

Code:
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int[] grade = new int[5];
        int[] outOf = new int[5];
        int[] percents = new int[5];
        

        int total = 0;
        int average;
        int percent;

        grade[0] = 70;
        grade[1] = 65;
        grade[2] = 120;
        grade[3] = 150;
        grade[4] = 30;

        outOf[0] = 210;
        outOf[1] = 100;
        outOf[2] = 150;
        outOf[3] = 200;
        outOf[4] = 50;

        for(int i=0;i<grade.length;i++)
        {
            total += grade[i];

        }

        average = total / 5;

        System.out.println("The total is " + total + "\nThe"
                + " average is " + average);
        }
        
        for(int j=0;j<grade.length;j++)
        {
           
            
        }
}
BuhRock is offline   Reply With Quote
Old 02-12-2011, 06:04 AM   PM User | #2
ShaneC
Codeasaurus Rex


 
Join Date: Jun 2008
Location: Redmond, WA
Posts: 659
Thanks: 31
Thanked 100 Times in 94 Posts
ShaneC is on a distinguished road
You've got everything pretty much set up and good to go. Where you're probably encountering your problem is when it comes to casting. Because the variables are integers, calculating the percentage will reduce to 0.

You will need to cast to the proper format, then cast to integer. Like so:

PHP Code:
percents[j] = (int)( ( (float)grade[j] / (float)outOf[j] ) * 100 );
System.out.println"Percentage of Grade " " is " percents[j] ); 
That code would go in that empty for loop of yours.
__________________
Unless otherwise stated, any code posted is most likely untested and may contain syntax errors.
My posts, comments, code, and suggestions reflect only my personal views.
Web Portfolio and Code Snippets: http://shanechism.com
ShaneC is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 03:33 AM.


Advertisement
Log in to turn off these ads.