Help! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Help!

Write a method that takes an array of integers and returns the position of the first zero (0) that it finds in the array.

1st Nov 2017, 3:12 PM
Geena Nana
Geena Nana - avatar
5 Answers
+ 2
public class Program { public static void main(String[] args) { int[] numbers = {5, 29, 12, 0, 66, 1, -30, 0, 45}; int idx = getIndexOfZero(numbers); if (idx == - 1) { System.out.println("(!) No '0' element is found..."); } else { System.out.println("Index of first 0 is " + idx); } } public static int getIndexOfZero(int[] numbers) { for (int i = 0; i < numbers.length; i++) { if (numbers[i] == 0) { return i; } } return -1; } } Here it is. I used Tobias's example. That way it should print a message, if there is no '0' at all.
1st Nov 2017, 3:44 PM
Boris Batinkov
Boris Batinkov - avatar
+ 3
thanks😀
1st Nov 2017, 3:41 PM
Geena Nana
Geena Nana - avatar
+ 3
thank you.i needed a return statement
1st Nov 2017, 4:03 PM
Geena Nana
Geena Nana - avatar
1st Nov 2017, 3:14 PM
Geena Nana
Geena Nana - avatar
+ 2
that's how my code looks. i need to add a method
1st Nov 2017, 3:14 PM
Geena Nana
Geena Nana - avatar