Im trying to make an array that just lists out some values, its the number of items sold in a day in a shop. and then, total those items in a seperate printf.

Heres my code so far, i also seem to have an issue where it just ignore my 0 , it will only show 1,2,3,4,5,6...ignoring the 0 totally.......heres the code...

public class InitArray5
{

    public static void main(String args[])
    {



    final int SALES_LENGTH=6; //declare constant
    int sales[]=new int[SALES_LENGTH];




    int sale[]={13,8,22,17,24,15,23};
    int counter=0;
    int sum;

    sum=0;
    System.out.printf("%2s%8s\n","index","value");


    while(counter<sales.length)
    {

    counter=counter+1;
    sum=sum+sale[counter];


    System.out.printf("%s%8s\n",counter,sale[counter]);




    }


    }


}

Edited 3 Years Ago by Dani: Formatting fixed

Please edit your posts: wrap your code around the [code] tags for a little more clarity, then we'll see what we can do for you. :)

remove this line from counter=counter+1; from the loop and do this instead inside your loop

sum+=sale[counter++];

Edited 4 Years Ago by ejosiah: n/a

its missing out your 0 because you are incrementing counter to 1 before using it as an index for sale

counter=counter+1;
sum=sum+sale[counter];

counter has already been incremented to 1 before you use it the first time. These two statements should be the other way round.
(or you could use ejosiah's version, which does the same thing more compactly or cryptically, depending on your experience level).

use a for loop instead when looping through arrays; for loops was made with arrays / collections in mind.

int[] myArray = {1, 3, 4, 5, 7};
for(int i=0; i < myArray.length; i++){
     System.out.printf("myArray[%s] => %s\n", i, myArray[i]);
}

or you could use Java 5 advanced for loop like so

int[] myArray = {1, 3, 4, 5, 7};
for(int item : myArray){
     System.out.printf("%s\n", item);
}

Edited 4 Years Ago by ejosiah: n/a

@ ejosiah

Ok i see , i used a for to start but thought i had a problem in there so i just changed to a while to try solve it. My issue was my bracketing of my print statement i think, it works now.....

if i wanted to then add all the individual values up into a total, i presume this is done just using a separate printf inside its own brackets at the bottom?

How do i isolate each individual value if you know what i mean, so they can be added together??

Thanks for your help, and everyone else too of course...

This question has already been answered. Start a new discussion instead.