user2875331
user2875331

Reputation:

Error regarding arguments when calling a method

I am getting an error when making the call to method findPosition. What I'm trying to do with the program is measure how long the algorithm runs on average, over 1000 iterations of it. Then I want to call the method and find the position of the value (if it is found) in the array. I'm getting a compiler error that the arguments being passed do not match the method. Specifically, the second argument is being taken as an int, even though I want to pass the value in an array. I can't find my error and am new to working with arrays, so thank you in advance if you can tell me where my mistake is.

import java.util.*;

public class AlgorithmRuntime 
{

static int num = 0;
static long total = 0;
static long average = 0;

public static void main (String[] args)
{
    boolean isValueInArray;
    int searchValue;

    do {
    // 1. Setup
    int size = 1000;
    long sum = 0;
    int[] iArray = new int[size];

    Random rand = new Random(System.currentTimeMillis());
    for (int i = 0; i < size; i++)
        iArray[i] = rand.nextInt();

    searchValue = rand.nextInt(1000) + 1;

    // 2. Start time
    long start = System.nanoTime();

    // 3. Execute algorithm
    for (int j = 0; j < size; j++)
    {
        if (iArray[j] == searchValue)
        {
            isValueInArray = true;
        }

        if (isValueInArray == true)
            findPosition(searchValue, iArray[isValueInArray]);
    }

    // 4. Stop time
    long stop = System.nanoTime();

    long timeElapsed = stop - start;

    total = total + timeElapsed;
    num++;

    } while (num < 1000);

    average = total / 1000;

    System.out.println("The algorithm took " + average 
            + " nanoseconds on average to complete.");
}
}

public int findPosition(int valueOfInt, int[] array)
{
  for (int i = 0; i < array.length; i++)
    if (array[i] == valueOfInt)
     return i;

  return -1;
}

Upvotes: 0

Views: 50

Answers (2)

Juned Ahsan
Juned Ahsan

Reputation: 68715

findPostion method accepts two arguments; one of type int and another of type int array. Here is the signature of findPosition:

public int findPosition(int valueOfInt, int[] array)

but you are passing it two int values as mentioned here:

findPosition(searchValue, iArray[isValueInArray];

isArray is an int array but iArray[isValueInArray] is an int value at index isValueInArray.

You need to pass an array as the second param instead of an int value.

Upvotes: 1

Xuan
Xuan

Reputation: 460

You need to pass in

if (isValueInArray == true) {
            findPosition(searchValue, iArray);
}

iArray[isValueInArray] will give you an int value and not the array.

Upvotes: 1

Related Questions