john la john la - 1 year ago 66
Java Question

Beginner searching through an array

I need to write a method that when passed a double array arr, and an int value target, returns the index of the first occurence of an item whose integer part equals target.

for example if arr = {1.2, 3.6, 5.2, 9.2, 5.6}, and target = 5, the target must return 2 and return -1 if array is null.

My code so far is

public static int yes(double[]arr, int target){
if (arr == null){
return -1;

for (int i= 0; i < arr.length(); i++){
if(arr[i] == target)
return i;

return 1;

and theres a compile error, I just dont understand converting between double and int? Thanks

Answer Source

Try casting your arr[i] to an int when checking to see if it is equal to your target:

for (int i= 0; i < arr.length; i++){
            if((int)arr[i] == target)
                return i;

Doing this will drop the decimal part of arry[i], making it integer, and thus comparable to your target.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download