Error message on return statement. - java

I am writing one method which having int prototype. But the method is showing error in editor by saying that Add return statement where return statement is already present. When I am adding another return it is working fine. I am writing in eclipse.
Here is my code :
private static int nextPrime(int n) {
if(n % 2 == 0)
n++;
for(; !isPrime(n); n+=2)
return n;
return n;
}
What is going wrong here. Thanks for help.

I think the problem is that your for loop has no body. Try giving it one:
private static int nextPrime(int n) {
if(n % 2 == 0)
n++;
for(; !isPrime(n); n+=2) { }
return n;
}
But really I think a for loop is the wrong kind of loop for this. Instead, you might want to use a while loop:
private static int nextPrime(int n) {
if (n % 2 == 0)
n++;
while (!isPrime(n)) {
n += 2;
}
return n;
}

The first return is in the scope of the loop, then the compiler force you to put one at the end of the function as you must ensure that on every path a return is made, alas the compiler cannot prove by itself that you always enter the loop...
It seems that your loop lack of a body...

Related

I ran into some problems with Recursion in Java

The task is to implement a program which counts how many different Sums of Primes there are for a given number sumtoBreak.
The Method primeSum should subtract all possible primes currprime from the number sumtoBreak until the sumtoBreak becomes zero and then return (in sum) a one for each possibilty. To account for all possibilities, in each recession step, it calls itself
with sumtoBreak - currprime plus
calls itself with the nextPrime.
My Problem is that java won't return anything unless the sumtoBreak is zero right at the beginning.
Would be glad for any advice!
Here's the code (I know that the parenthesis in the code with the nested if statements are redundant, but I just wanted to make sure, that's not the problem):
Here's the fixed code:
public class PrimeSum {
public static boolean isPrime(int primecandidate) {
int count = 0;
for (int i = 2; i <= primecandidate / 2; i++) {
if (primecandidate % i == 0)
count++;
}
if (count == 0)
return true;
else
return false;
}
public static int nextPrime(int currprime) {
int j = currprime + 1;
while (!isPrime(j))
j++;
return j;
}
public static int primeSum(int sumtoBreak, int currprime) {
if (sumtoBreak == 0) {
return 1;
} else {
if (sumtoBreak < 0 || currprime > sumtoBreak) {
return 0;
} else {
return primeSum(sumtoBreak, nextPrime(currprime)) + primeSum(sumtoBreak - currprime, currprime);
}
}
}
public static void main(String[] args) {
System.out.println(primeSum(Integer.parseInt(args[0]), 2));
}
}
This doesn't answer your question, but corrects an error in your isPrime Method and computes the result much faster:
private static boolean isPrime(final int primecandidate) {
if ( primecandidate < 2) { // 0 & 1 are NOT Prime
return false;
}
if ((primecandidate & 0x1) == 0) { // Even is NOT Prime...
return primecandidate == 2; // ...except for 2 (and 0).
}
for (int i = 2, iMax = (int) Math.sqrt(primecandidate); i <= iMax; i++) {
if (primecandidate % i == 0) {
return false;
}
}
return true;
}
Note the following:
the final argument primecandidate is marked final
it corrects the result for 0 & 1 to false
the method is marked private
the iMax is Sqrt(primecandidate) & not primecandidate / 2
iMax is calculated once, instead of every iteration
I use a strategy I call "if you're done, be done."
Meaning: don't set a flag (in your case count), just get out!
Please note also, there is an apache commons Math3 function...
org.apache.commons.math3.primes.Primes.isPrime(j)
It is significantly slower for smallish values (<= Short.MAX_VALUE)
It is somewhat faster for largeish values (ca. Integer.MAX_VALUE)
There is also a BigInteger.isProbablePrime(...) function, but my Benchmark suggests it is rather slow.
I hope this helps a little?
Some things you might have missed:
in a function, a return statement terminates (break) the function immediatly. So in
if(...) { return ...; }
else {...}
→ else is redundant, as if the condition is true, the function is already terminated (break)
Something like a==0 has a boolean value (true or false). So
if(count==0) { return false; }
else { return true;}
can be shortened to return count!=0;
I recommend to always use braces, because something like if(i==0) ++i; break;, means if(i==0) {++i;}. break; will be called in any case.
public static boolean
isPrime(int n)
{
if(n==0 || n==1) { return false; }
for(int i= 2; i <= n/2; ++i)
{
if(n%i == 0) { return false; } //we know, n is not a prime,
//so function can break here
}
return true; //since for all values of i, the function did not break,
//n is a prime
}
I wish you a lot of motivation to code for the future!

Why return should be last line of my method? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 days ago.
Improve this question
I am trying to solve this problem:
Solve for square root.
And this is my code:
public class Solution {
public int sqrt(int A) {
for(int i=0;i<A;i++)
{
if(A%i==i)
{
return i;
}
}
for(int i=A;i>0;i--)
{
for(int j=0;j<A;j++)
{
if(A%j==j)
{
return j;
}
}
}
}
}
But after I try to run it on Interview Bit it shows an error:
./Solution.java:23: error: missing return statement
}
^
1 error
Now I am not able to even run my code.
Your method should have a return, that's the rules. It's not necessarily in the last line, but there should never be a case when there is no return. With your custom algorithm, your return is always conditional and the compiler will not know in advance whether those conditions will ever be true.
So, the problem is like this:
Lets assume that A is a negative number (e.g. -1):
The 1st loop body will never be executed since i (0) is greater then A (-1)
for(int i=0;i<A;i++)
The 2nd loop body will never be executed since i (-1) is smaller then 0.
for(int i=A;i>0;i--)
therefore - we arrived to the end of the function and there is nothing to return even that the function declared as returning int.
Basically - all paths must have return statement (unless the function is void - and in such a case the return statement can be implicit)
If you have declared a method with expects a return type then you must have to take care of all the scenarios of executing all the blocks in that method. Whatever is the code block the method is executing it must return something of the required type.
Find the missing block in your code below :
public class Solution {
public int sqrt(int A) {
for(int i=0;i<A;i++)
{
if(A%i==i)
{
return i; // returning an int here which is correct
} // what if the the 'if' condition is not met. Add a return type for else
}
for(int i=A;i>0;i--)
{
for(int j=0;j<A;j++)
{
if(A%j==j)
{
return j;
} // same what if the condition is not met add a return in 'else' if required.
}
} // if you are not adding any return in the else block. which is not required in your current program then just add a default return to your function.
}
}
For some more information check this
Although you do have two return statements, the compiler is specifying that it still does not have anything to return if both of your conditions aren't met (false).
So to understand, you would have to ask yourself: What would happen if both of these conditions are false? (Conditions being if (A % i == i) and if (A % j == j))
Solution:
public int sqrt(int A) {
for (int i = 0; i < A; i++) {
if (A % i == i) {
return i;
}
}
for (int i = A; i > 0; i--) {
for (int j = 0; j < A; j++) {
if (A % j == j) {
return j;
}
}
}
return -1; //-1 or 0 is widely returned by default to represent a failed function
}
So basically, when creating a method which is expecting something to be returned, you have to return it outside any conditional statements.
Your method Signature is :
Integer sqrt(int A)
Which says that your method body must return an Integer.
Now, in your code ,you are returning value but when certain condition is true.What if that condition is not true.Compiler is smart enough to find that ,in that case,there is no return value,hence the error.
Return should be the last line of your method not the class. As you have declare that method as 'int type', so you should have returned an int value. Compiler can't identify whether that 'if condition' reaches true in all inputs. so you should place a return 0 at the end of the method.
You're not assuring a return value in every state of your method. Besides that, your code doesn't makes sense.
1.You're dividing by zero in the first if loop (don't do that, it's forbidden)
2.The condition i > 0 in the second for loop will always be false.
At the end it should look something like this
public int sqrt(int A) {
for () {
if () {
return i;
}
}
for () {
for () {
if () {
return j;
}
}
}
return 0;
}
If the only thing you want to do is to square a number, use the Math.pow method, don't reinvent the wheel!
int i = 2;
int square = Math.pow(i, 2);

Boolean use in an if statement

public static int search(int[] a, int target)
{
int i=0;
boolean found = false;
while((i<a.length) && ! found)
{
if (a[i] == target)
{
found = true;
}
else i++;
}
if (found) return i;
else return -1;
}
I dont understand the if statement part. So how i am reading it in my head is found is set to false. If not found...so if not false (since found = false), do whatever. So basically im reading it as a double negative and seeing if (true) dow whatever. But it doesnt make sense. I know its not an inifite loop and it runs fine but I dont get the logic, it must not be a double negative. Thanks!
EDIT:
So i get that we could just return i, much easier yes I agree. I just am having trouble with the logic of the boolean value being used in the loop with the not "!" symbol.
Basically if i wrote this i would say (ignoring everything else)
found = true //found is true to begin with
while (!found) //while not true
continue to next index //continue until ....actually i'm getting very confused now because to break the loop we would continue until found is false which logically is backwards
EDIT: Thank you everyone for your comments!! It all helped me understand it!
public static int search(int[] a, int target)
{
for (int i = 0; i < a.length; i++){
if (a[i] == target) return a[i]; // or i if you want to get ingex of searched element
}
return -1;
}
The ! operator inverts the following logical statement (logical not gate).
Because !false is true, it means it is not a double negative.
!found means the same thing that it means in English, i.e. "not found". The entire condition with i<a.length reads "while i is a valid index and [target is] not found", which is pretty close, given that you know that "not found" refers to target
You can simplify this loop to avoid Boolean variable:
while(i < a.length) {
if (a[i] == target) {
return i;
}
i++;
}
return -1;
Do you think it is easier?
public static int search(int[] a, int target) {
for (int i = 0; i < a.length; i++) {
if (a[i] == target) {
return i;
}
}
return -1;
}
Let me break it down into a few parts for you:
while((i<a.length) && ! found)
So you start with false. As !false evaluates to true, you continue the loop until found is true which will make the whole condition false, causing you to break the loop.
i<a.length: while i<length returns true, continue the loop.
You basically want found to be false and i<length for the loop to continue. If any of the condition isn't met, you break the loop (check out the &&).
if (a[i] == target) found = true;
else i++;
This is simple: if the number is found, make the found boolean true. This will cause the next iteration condition to evaluate as false, causing the loop to break.
The code loops over the array of ints while found is false.
During the loop it compares the current array value in a (a[i]) to the target, If the values are the same, it sets found to be true.
Thus after the loop it checks if found is true, and if it is it returns i, the index of the last comparison value.
At the start of the loop found is false, so the while loop will start. Once a value is found, found is set to true and the loop stops.
I would rewrite the loop however:
public static int search( int[] a, int target)
{
int foundIdx = -1;
for( int i = 0; i < a.length && foundIdx < 0; i++ )
{
if( a[i] == target )
{
foundIdx = i;
break;
}
}
return foundIdx;
}
So, I think your doubt is on the while statement, but I'll put some comments on all the code to try to explain what it does:
public static int search(int[] a, int target)
{
int i=0;
boolean found = false;
// While i index is less than the array length AND item hasn't been found (negation of the found variable), keep iterating on the loop. If not (if any of this two conditions aren't met), continue.
while((i<a.length) && ! found)
{
/* If the targeted item has been found, set found boolean to true, so this loop will stop before next iteration
*/
if (a[i] == target)
{
found = true;
}
// If targeted item is not this one, increase the index for next iteration
else i++;
}
/* This condition only will be met if we exit the loop because we found the target. In that case, we will return the index in the array of that index. If we "finished" the array without finding it, we will return -1, meaning "it wasn't found".
*/
if (found) return i;
else return -1;
}
Set the boolean found = false; because you have not found what you're looking for yet, then while (i<a.length) and ! found means that if you have not reached the end of the array and you have not found what you're looking for do
{
if (a[i] == target)
{
found = true;
}
else i++;
}
If you found it change the variable found to true which with the negation operator ! will be changed to false and the && will take you out of the while loop since one of the 2 conditions is not true any more.
In other words if found is false then in the loop is true because you have ! (not) found it. And if found is true then in the loop is false because you have found it.
What you think about using IntStream ?
public static int search(int[] a, int target) {
final OptionalInt index = IntStream.range(0, a.length).filter(i -> a[i] == target).findFirst();
return index.isPresent() ? index.getAsInt() : -1;
}

Fixing Exception in thread "main" java.lang.StackOverflowError

What is the reason of the StackOverflowError? I was trying it for a while but still can't get why it happens, and how to fix it.
The formula used in the code is a requirement.
public static long fib(long n){
if(n == 1 || n == 2)
return 1;
else if(n > 2 && n%2 == 0)//even
return fib((n/2+1)*(n/2+1)) - fib((n/2-1)*(n/2-1));
else //odd
return fib(((n+1)/2)*((n+1)/2)) + fib(((n-1)/2)*((n-1)/2));
}
public static void main(String[] args){
for(int i = 1; i <= 10; i++)
System.out.println(fib(i)+" ");
}
Not really sure what you are trying to achieve with your method, but by just adding some System.out.println to your code you can see what you are getting in each recursive call. For what I see your "odd" call is getting into an infinite loop and that is why you got that StackOverflowError error, Typically this is caused when your recursive functions doesn't have the correct termination condition, that is to say, it ends up calling itself forever.
For the way you start your code and the "fib" method name, it looks like you are trying to perform Fibonacci, which can be done in a simpler way:
public static int getFibonacci(int n) {
if (n == 1) {
return 1;
}
if (n == 2) {
return 1;
}
return getFibonacci(n - 1) + getFibonacci(n - 2);
}

Return type with integers

I'm making a small program that determines the minimum integer of 3 integers. I'm having problems returning the integers back into the variable answer.
Here Is how I imagine the program working;
PROGRAM RUNS:
Looks for Method called "Minimumum" with the listed argument.
Determines the minimum integer and returns it back to the method Minimum
This value gets stored in the answer variable
Code:
public class Method {
public static void main(String[] args) {
int answer = Minimum(20, 40, 50);
}
public static int Minimum(int first, int second, int third) {
if ((first < (second) && (first < third))) {
return first;
} else if ((second < (first) && (second < third))) {
return second;
} else if (((third < first) && (third < second))) {
return (third);
} else {
System.out.println("error");
}
}
}
You need to return a result in all cases, so your else block is incorrect. Do you really think there is a fourth case ? No, there isn't : there are three integers so the minimum is one of those three, meaning there only are 3 cases... Simply remove the else block. By the way, why do you use so many parentheses ? It's useless, and unreadable.
public static int Minimum(int first, int second, int third){
if (first < second && first < third)
return first;
else if (second < first && second < third)
return second;
else
return third;
}
As noted by the others, this is not sufficient to make your method correct. Indeed, you don't care about strict inequality here because when two numbers are the same, you can choose either of them as the minimum. This code breaks if the two first parameters are equal. To fix it, simply use <= instead of < (everywhere).
Your code looks a bit complicated.
int Minimum(int first, int second, int third) {
int min = first;
if (second < min) {
min = second;
}
if (third < min) {
min = third;
}
return min;
}
This looks creepy, but it should do it.
Hope it helps to understand.
You have to return in your final else block. But you could simplify your code with Math.min(int, int). Something like,
public static int Minimum(int first, int second, int third) {
return Math.min(first, Math.min(second, third));
}
Minimum function should always return the integer value in any case. After else, add return statement.
In Java 8+ your method could also look as follows:
public static int minimum(Integer val1, Integer val2, Integer val3){
List<Integer> list = Arrays.asList(new Integer[]{val1, val2, val3});
return list.stream().min((Integer v1, Integer v2) -> v1 < v2 ? 0 : 1 ).get();
}

Categories

Resources