Reputation: 83
Why does it say the method must return of type int? The returns are integers
public static int search(int[] nums)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What value do you want?");
int value = keyboard.nextInt();
for(int i=0;i<nums.length;i++)
{
if(nums[i] == value)
return nums[value];
else
return -1;
}
}
Upvotes: 2
Views: 7934
Reputation: 5637
if nums
is empty, the for loop never gets executed, thus you return nothing
do this
public static int search(int[] nums)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What value do you want?");
int value = keyboard.nextInt();
for(int i=0;i<nums.length;i++)
{
if(nums[i] == value)
return nums[value];
else
return -1;
}
return 0; // default value
}
Upvotes: 2
Reputation: 1533
Not all paths returns something.
You could avoid that kind of mistake by adding a return after the for
loop, or by using a return variable. It also look like your trying to search the array for the number the user typed. If so, you don't want the else case, or it will only check for the first number in nums
.
public static int search(int[] nums)
{
int ret = -1;
Scanner keyboard = new Scanner(System.in);
System.out.println("What value do you want?");
int value = keyboard.nextInt();
for(int i=0;i<nums.length;i++)
{
if(nums[i] == value)
{
ret = nums[value];
break;
}
}
return ret;
}
Upvotes: -1
Reputation: 272417
Whilst your return types inside the loop are of type int
, your loop isn't guaranteed to actually run, and you don't have a return value (and hence type) in the scenario that your loop doesn't run.
Upvotes: 0
Reputation: 41240
in case nums[]
is empty array or null. (But null value makes a nullpointer exception nums.length
.) In that case loop will not execute and it would be a void return so to avoid this situation you must declare a default return statement.
Upvotes: 0