Ok so I'm doing some practice questions, and this one is trippin me up a bit. I need to create an array that stores data 0.0, 0.1, 0.2, 0.3, all the way to 20.0. Then I have to compute the sums of the elements that are not integers (i.e 0.0, 1.0, 2.0, 3.0...onward to 20.0).

this is what I have come up with so far...but I am unsure if this is truly the most efficient way or even entirely correct. suggestions/help greatly appreciated! our class textbook is entirely out of date and useless

``````class Test1{

public static void main(String[] args){

double[] array = new double[201];
for (int i = 0; i <= 200; i++){
array[i] = i/10.0;
//System.out.println(array[i]);
}
int sum = 0;
sum = 0;
for (int i = 0; i < array.length; i++){
if(array[i]!=(int)(array[i])){//array[i]is not int
sum += array[i];
}
}
System.out.print(sum);

}
}``````

Learn to use code tags. click the CODE button, when making a post.

Always do this:

``````double[] array = new double[201];
for (int i = 0; **i < array.length**; i++){
``````

when you print the array values, do you get what you wanted? Is the total sum correct? The code looks ok, What errors do you get?
Calculate the sum with a piece of paper and see if the sum is correct.

javaaddict when he does that wouldn't it return an array out of bounds exception error?

javaaddict when he does that wouldn't it return an array out of bounds exception error?

NO, NO, ..... NO.

Why would it?
In java indexes start from 0 till length-1: `i=0;i<array.length;`

NO, NO, ..... NO.

Why would it?
In java indexes start from 0 till length-1: `i=0;i<array.length;`

Well i tried it and it did...must have been something i did :P

Well i tried it and it did...must have been something i did :P

What kind of code did you use? Because I find it strange and I am curius.

What kind of code did you use? Because I find it strange and I am curius.

``````class Test1{

public static void main(String[] args){

double[] array = new double[201];

for (int i = 0; i <= array.length; i++){

array[i] = i/10.0;
//System.out.println(array[i]);
}

int sum = 0;
sum = 0;

for (int i = 0; i < array.length; i++){

if(array[i]!=(int)(array[i]))
{
//array[i]is not int
sum += array[i];
}
}

System.out.print(sum);

}

}``````

I used this code, but i'm pretty sure its the same code as JAK3CAL except I replaced the first for loop middle statement with < array.length.

Maybe I messed up somewhere i don't know :P

This: `for (int i = 0; i <= array.length; i++)` Will throw an Exception. (i=0, ..., array.length)

This: `for (int i = 0; i < array.length; i++)` Will NOT throw an Exception. (i=0, ..., array.length-1)