Entering elements into an array

TravJ14 :

I'm trying to enter in elements into the array with unknown values of the elements or unknown amount of elements

public class Sales
{
  public void salesAmount()
  {
Scanner scan = new Scanner(System.in);

int sum = 0; 
int salespeople = 0;

    //Create printstatement to ask the user to ("enter the number of sales people");
   System.out.println("Enter the number of sales people: ");


   //store the response in salespeople
   salespeople = scan.nextInt();


    //Create an int array called sales that will have the number entered by user as the number of elements
    int[] sales = new int[salespeople];


    //create a for loop that will loop through the array sales.    
    for(int i = 0; i < salespeople; i++)
{
     //Create print statement that says:  ("Enter sales for salesperson " + i + ": ");
      System.out.println("Enter sales for salesperson " + i + ": ");
      sales[i] = scan.nextInt();
      //store response in sales[i] 
      sum = sum + sales[i];

    }

    System.out.println("Salesperson\tSales");
    System.out.println("--------------------");

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

    System.out.println("\nTotal sales: " + sum);
      }
    }

I'm printing it all out on a second file, which is the code below:

public static void main(String[]args)
{
  Sales sales = new Sales();
  sales.salesAmount();
}

The expected results should be the sum of all of the entered numbers, but my result was the sum of them and then doubled.

Jitendra Singh :

In your second 'for loop', remove the sum. You do the addition two times in 2 loops

for (int i=0; i<sales.length; i++)
    { 
      System.out.println(i + "\t" + sales[i]); 
      //sum += sales[i];
    }

    System.out.println("\nTotal sales: " + sum);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=157540&siteId=1