简体   繁体   English

对于循环打印数组中的值总和一次,不断重复

[英]For loop print sum of values from array only once, keeps repeating

I am aiming to create a method which prints the total cost of all employees that are added to an array. 我的目标是创建一种方法,该方法可以打印添加到阵列中的所有员工的总成本。 Salary is added to the array using: 使用以下方法将薪水添加到数组中:

**Scanner sal = new Scanner(System.in);      
        System.out.println("Enter annual employee salary $");
        int salary = sal.nextInt();
        salaryArray[index] = salary;

        index++;**  

I then use the following to get the sum: 然后,我使用以下代码获取总和:

  public static void cost()
  {
    int sum = 0;

    for (int i = 0; i < salaryArray.length; ++i)
    {
      System.out.println(sum += salaryArray[i]);
    }
  }

The problem is it prints out the result multiple times, I would like it to print only once, giving only one result. 问题是它会多次打印出结果,我希望它只打印一次,只给出一个结果。 Further changes seem to break my code when I try to fix it. 当我尝试修复它时,进一步的更改似乎破坏了我的代码。

For each salary added you print the current sum. 对于增加的每个薪水,您都将打印当前金额。
You want to print the sum after the loop. 您要在循环后打印总和。 So do that 那样做

As improvement, you could use a more meaningful name for the method as method names should generally start by an infinitive verb. 作为改进,您可以为该方法使用一个更有意义的名称,因为方法名称通常应以不定式动词开头。
You could also use an enhanced for as the index variable is only used to iterate every element. 您也可以使用增强的for因为index变量仅用于迭代每个元素。 The enhanced for provides it in a cleaner way. for的增强for以一种更清洁的方式提供它。

 public static void displayCost()  {
    int sum = 0;    
    for (int salary : salaryArray){
      sum += salary;
    }
    System.out.println(sum);
  }
public static void cost()
  {
    int sum = 0;

    for (int i = 0; i < salaryArray.length; ++i)
    {
      sum += salaryArray[i];
    }
System.out.println(sum);

  }

Just show sum variable once . 只显示一次sum变量。

You are printing the result in a for loop, of course it would print multiple times. 您要在for循环中打印结果,当然它将打印多次。 why not try this; 为什么不试试这个呢?

for(int i = 0; i < salaryArray.length; i++){
sum += salaryArray[i];//getting the value of the sum first
}
System.out.println(sum);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM