Получение суммы из массива - PullRequest
0 голосов
/ 28 ноября 2018

Я не могу понять, почему я не могу получить сумму моего массива для работы.

Я пытаюсь получить среднее значение из массива 10, вмененного пользователем, у пользователя есть выборчтобы остановить ввод, введя число 0 или ниже.программа автоматически превратит все обрезанные числа в 0.

Мне просто нужен способ получить сумму всех чисел из массива.

Я попытался сделать что-то с переменной с именемсумма внутри метода getNames, но я не уверен, что смогу отправить его на главную.

package arraydowhile;

import java.util.Scanner;
import java.lang.*;
import static java.lang.Float.sum;

/**
 *
 * 
 */
public class Arraydowhile {
    //constants
    static final int MAXIMUM_NUMBERS = 10;
    static final int MINIMUM_NAMES = 0;
    static final float AVERAGE_COUNT = 10;
    static Scanner input = new Scanner(System.in);

    public static void main(String[] args)
    {
        int[] numbers = new int[MAXIMUM_NUMBERS];   // an array that can store 10 whole numbers- default value of each element is 0
        float[] marks = {8.5f, 4, 6.75f, 3.5f, 10}; //an array that can store real numbers- default size is 5  
        float[] names ;                            //an array declaration but no storage allocation yet
        float[] averageArray ;
        float[] average ;
        float sum = 0;
        float total =0;

        System.out.println("The elements of the 'numbers' array");
        System.out.println("Index\t\tValue");
        for(int counter = 0; counter < MAXIMUM_NUMBERS; counter++)
        {
            System.out.printf("%d\t\t%d%n", counter, numbers[counter]);
        }//for
        System.out.println("-------------------------------------------------------------");

        //Every array object knows its own length and stores it in a length instance variable. 
        System.out.printf("There are %d elements in the marks list%n", marks.length);
        for(int counter = 0; counter < marks.length; counter++)
        {
            if (counter!= marks.length-1){
                System.out.printf("%.2f, ",marks[counter]);
            }//if
            else
            {
                System.out.printf("%.2f",marks[counter]); //last element does not need a comma after it
            }//else
        }//for
        int totalNames = 10;



        names = new float[totalNames];

        for(float name: names)
        {
            System.out.println(name);
        }//for


        names = getNames(totalNames);

    //  total = total + names[totalNames];
     //   average = new float[totalNames];
     //   average = getAverage(average);

        //calculate the average of all the numbers
        //System.out.println("The Average was "+total / AVERAGE_COUNT);



        if(names != null)
            displayNames(names);
         else{
            System.out.println("------------No numbers were provided------------------");
        }//else

System.out.println("The Sum is "  );
    }//of main


    private static float[] getNames(int totalNames)
    {
        float[] names = new float[totalNames];
        int counter = 0;
        float name;
        float total = 0;
        float sum = 0;
        float average = sum / counter;
        System.out.printf("Please input a real number,  %d must be given. You have the option to quit anytime by entering a number from 0 or lower %n", totalNames);
        do{
            System.out.printf("Please input number %d: ", counter+1);
            name = input.nextFloat();
            sum = sum+name;

          //  System.out.println("The Sum was "+sum);
         //   System.out.println("The Average was "+ sum / counter);

            if(name == 0){
                System.out.println("You have not provided a number, and nothing will be saved");
                break;
            }
            else if (name < 0)
            {
                System.out.println("You have decided to end input");
                break;
            }
            else
            {
                names[counter] = name;
                counter++;
            }//if
           // System.out.println("The Sum was "+sum);
           // System.out.println("The Average was "+ sum / counter);
        }

        while(counter < totalNames);

        if(counter == 0)
            return null;
        else
            return names;


        // names[counter] = s.nextFloat();
        //  sum = sum + a[counter];

    //    total = names[totalnames];

    }// of getNames










    private static void displayNames(float[] names)
    {
            //System.out.printf("%d names were entered.%n",names.length);
            System.out.println("-----------------List of numbers-------------------");
            for(float name: names)
            {
               // if(name != null)
                    System.out.println(name);

            }//for



    }//displayNames


}//of ArrayDemonstration

1 Ответ

0 голосов
/ 28 ноября 2018

Вы можете получить сумму массивов, как показано ниже,

int sum = 0;
for(int i = 0; i < sampleArray.length; i++){
    sum += sampleArray[i];
}
...