8.3k views
1 vote
JAVA

Write a method that takes an int[] array and an int value and returns the first index at which value appears in the array.

If the value does not exist in the array, return -1

For example:

search(new int[]{10, 20, 30, 20}, 20)
Should return 1

Because 20 first appears at index 1 in the array.

search(new int[]{10, 20, 30, 20}, 40)
Should return -1

public int search(int[] array, int value)
{
}

User Edd Inglis
by
3.9k points

2 Answers

2 votes

Answer:

Answer is in the attached screenshot!

Step-by-step explanation:

Just iterate through the values in the list - if the value at the index is equal to the one you are searching for, just return that index. If no value is returned then return with -1!

JAVA Write a method that takes an int[] array and an int value and returns the first-example-1
User Juangcg
by
4.7k points
2 votes

Answer:

public static void main()

{

Scanner console = new Scanner(System.in);

System.out.println("Enter in a value");

int a = console.nextInt();

int[] array = {1,2,3,4,5};

int a1 = search(array, a);

System.out.println(a1);

}

public static int search(int[] array, int value)

{

boolean okay = true;

int b = 0;

for(b = 0; b<=array.length-1; b++)

{

if(value==array[0])

{

okay=true;

}

else

{

okay = false;

}

}

if(okay = true)

{

return b;

}

else

{

return -1;

}

}

Step-by-step explanation:

User FlyingLizard
by
4.1k points