Question

Working on a project where the user input determines the size of an array. Afterwards the user inputs values and receives the sum. Finally the program shows the user the percentage of each value to the total. For example if the array size is 4 and a[0] = 2, a[1] = 1, a[2] = 1, and a[3] = 2 it will show "2, which is 33.333% of the sum" "1, which is 16.666% of the sum" etc. The problem I have is that after the array and sum are determined and I try to find the percentage I get 0. Is the sum reset to 0 since it's a different for loop?

import java.util.Scanner;

public class CountIntegersPerLine
{
    public static void main(String[] args)
    {
        int elements;
        int arraySize;
        int sum = 0;
        int percentage;
        System.out.println("How many numbers will you enter?");
        Scanner keyboard = new Scanner(System.in);
//Length of array is determined by user input
        arraySize = keyboard.nextInt();
        int[] array = new int[arraySize];
        System.out.println("Enter 4 integers, one per line");
        for (elements = 0; elements < arraySize; elements++)
        {
//Gather user input for elements and add the total value with each iteration
    array[elements] = keyboard.nextInt();
    sum = sum + array[elements];
        }
        System.out.println("The sum is " + sum);
    System.out.println("The numbers are:");
    for (elements = 0; elements < arraySize; elements++)
    {
//Display the percent that each value contributes to the total
    percentage = array[elements] / sum;
    System.out.println(array[elements] + ", which is " + percentage + " of the sum.");
    }
        System.out.println();
}

}

Was it helpful?

Solution 2

Try declaring the sum variable as a double (or float):

double sum = 0.0;

Why? because in this line:

percentage = array[elements] / sum;

... You're performing a division between two integers, and all the decimals will be lost. You can verify that this is indeed the case, for example try this:

System.out.println(1/3); // it'll print 0 on the console

The solution to this problem is to have either one of the division's operands as a decimal number, by declaring as such their types (as I did above) or by performing a cast. Alternatively, this would work without changing sum's type:

percentage = array[elements] / ((double)sum);

OTHER TIPS

Integer division will result in a zero value when the numerator is less than the denominator. You should declare percentage as a float or a double.

    int percentage;
    ...
    ...
    ...
    percentage = array[elements] / sum;

and you will need to cast the division operation in your case to preserve the value:

percentage = (double)array[elements] / sum;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top