Error "Missing return statement" [duplicate] - java

This question already has answers here:
"Missing return statement" within if / for / while
(7 answers)
Closed 7 years ago.
I am running this java code and I am getting an error "missing return statement"
Please help. I am running using cmd in windows.
public class Fibonocci {
public static void main(String[] args) {
int i, limit, c;
i = 0;
limit = 5;
System.out.println("Fibonocci series :");
for (c = 1; c <= limit; c++) {
System.out.println(fib(i));
System.out.println("/n");
i++;
}
}
public static int fib(int p) {
if (p == 0) {
return 0;
}
if (p == 1) {
return 1;
} else if (p > 1) {
return (fib(p - 1) + fib(p - 2));
}
}
}

Your code doesn't return anything if p<0.
You can change it to :
public static int fib(int p){
if (p<=0) // or perhaps you wish to throw an exception if a negative value is entered
return 0;
else if (p==1)
return 1;
else // when you end the if statement in else instead of else-if
// your method is guaranteed to return something for all inputs
return(fib(p-1)+fib(p-2));
}

You are missing a default return. You are returning from if and else if.
What if both conditions not satisfied ? You need to provide that as well.
I would like to suggest to return -1 id both conditions not satisfied which is for negative numbers negative
public static int fib(int p) {
if (p == 0)
return 0;
else if (p == 1)
return 1;
else if (p > 1)
return (fib(p - 1) + fib(p - 2));
else
return -1;
}

Related

Method with boolean return type not working inside main()

I had static method which is to find out prime number and it is working fine but the same method i am trying to keep inside main method it is throwing errors by stating illegal modifiers for parameter and void method does not return value
the same code is working fine outside of main method, any one plz sugggest me why it is not working in main() . Thanks ..!!
My method
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
Inside main() with lot of error message
inside main
Solution
Thanks Logan --- need to add methods outside main method
my working code is added below
public class Squar {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
Squar s = new Squar();
//System.out.println(s.isPrime(num));
scan.close();
System.out.println("M2 "+s.isPrimeNumber(num));
}
public boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
You are getting this error because Java does not support nested function.
You are implementing method inside other method, that is not possible. to nest methods use lambdas in java 8.
have a look at Can methods in java be nested and what is the effect? [closed]

Confused about return value for a public int method [duplicate]

This question already has answers here:
Missing return statement for if/else statement
(8 answers)
Closed 7 years ago.
I'm finishing up a project for school, but I have to create a method that returns a value -1, 0, or 1 based on the alphabetical order of the first letter of name objects. I'm confused on why I keep getting an error asking me for a return value, perhaps I can't see what I'm missing but any help would be appreciated (I'll probably see a teaching assistant tomorrow or the day after).
public int compareTo(Name nameObject) {
if (middleName.equals(null)) {
if (getLastName().charAt(0) < nameObject.getLastName().charAt(0)) {
return -1;
} else if (getLastName().charAt(0) > nameObject.getLastName().charAt(0)) {
return 1;
} else if (getLastName().charAt(0) == (nameObject.getLastName().charAt(0))) {
if (getFirstName().charAt(0) < nameObject.getFirstName().charAt(0)) {
return -1;
} else if (getFirstName().charAt(0) == nameObject.getFirstName().charAt(0)) {
return 0;
} else if (getFirstName().charAt(0) > nameObject.getFirstName().charAt(0)) {
return 1;
}
}
} else {
if (getLastName().charAt(0) < nameObject.getLastName().charAt(0)) {
return -1;
} else if (getLastName().charAt(0) > nameObject.getLastName().charAt(0)) {
return 1;
} else if (getLastName().charAt(0) == (nameObject.getLastName().charAt(0))) {
if (getFirstName().charAt(0) < nameObject.getFirstName().charAt(0)) {
return -1;
} else if (getFirstName().charAt(0) > nameObject.getFirstName().charAt(0)) {
return 1;
} else if (getFirstName().charAt(0) == nameObject.getFirstName().charAt(0)) {
if (getMiddleName().charAt(0) < nameObject.getMiddleName().charAt(0)) {
return -1;
} else if (getMiddleName().charAt(0) == nameObject.getMiddleName().charAt(0)) {
return 0;
} else if (getMiddleName().charAt(0) > nameObject.getMiddleName().charAt(0)) {
return 1;
}
}
}
}
}
Your "else if" line(s) are dangling. E.g.,
} else if (getLastName().charAt(0) == (nameObject.getLastName().charAt(0))) {
Any "else if" needs to follow with an "else" -- or just a return value -- to ensure something is returned.

fibonacci recursive method with special output

I'm looking to generate a specific output with my fibonacci recursive method. I already have the recursive code. However the output should display the fibonacci number(one per line) and also the ratio of the current and previous fibonacci numbers on each line.
(if user enters 5)
Fib#1=0
Fib#2=1
Fib#3=1; 1/1=1
Fib#4=2; 2/1=2
Fib#5=3; 3/2=1
this is the code i have so far:
if(n == 0)
return "0";
else if(n == 1)
return "1";
else
return FibonacciCalc(n - 1) + FibonacciCalc(n - 2);
How do i make that output? Should i return a String or make a different print method? Thanks
The problem with this recursive function is that it would be very inefficient as it has the calculate the whole range every time. Better to do this in a loop.
int beforeLastNumber = 1;
int lastNumber = 1;
System.out.println("0");
System.out.println("1");
for(int number=2; number<max; number++) {
int nextNumber = beforeLastNumber + lastNumber;
beforeLastNumber = lastNumber;
lastNumber = nextNumber;
System.out.println(nextNumber);
}
The above keeps a running total of where we're at, which avoid recalculating a sum of lots of numbers to get the higher ones.
Try this:
public class fib {
public static int FibonnaciCalc(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return FibonnaciCalc(n - 1) + FibonnaciCalc(n - 2);
}
public static void main(String[] args) {
final List<Integer> fibList = new ArrayList<Integer>();
int limit = 5;
for (int i = 0; i < limit; i++)
fibList.add(FibonnaciCalc(i));
int tmp = 0;
for (int i=0;i<fibList.size();i++) {
tmp=i+1;
if (i <2)
System.out.println("Fib#" + tmp + "=" + fibList.get(i));
else
System.out.println("Fib#" + tmp + "=" + fibList.get(i)+"; "+fibList.get(i) +"/"+fibList.get(i-1)+"="+fibList.get(i)/fibList.get(i-1));
}
}
}
Recursive fibonacci output
class FibonacciContext {
int beforePrevious;
int previous;
public FibonacciContext(int beforePrevious, int previous) {
this.beforePrevious = beforePrevious;
this.previous = previous;
}
public int getBeforePrevious() {
return beforePrevious();
}
public int getPrevious() {
return previous;
}
public int getNext() {
return beforePrevious + previous;
}
public FibonnaciContext getNextContext() {
return new FibonnaciContext(previous, getNext());
}
}
public FibonacciContext outputFibonacciNumbers(int maxIndex) {
// 0 and 1 are 0 and 1 - non recursive termination
if (maxIndex<2) {
System.out.println(maxIndex);
return new FibonnaciContext(0, maxIndex);
}
// output all previous numbers before this one
FibonnaciContext context = outputFibonacciNumbers(maxIndex-1);
// print out this one
System.out.println(context.getNext());
// context passed back to the recursive call
return context.getNextContext();
}
Try this one:
public static void main(String[] args) {
new Main().f(5);
}
private void f(final int i) {
if (i > 2) {
f(i - 1);
System.out.println(String.format("Fib#%1$d=%2$d; %2$d/%3$d=%4$d", i, fib(i-1), fib(i-2), fib(i-1)/fib(i-2)));
} else if (i > 0) {
f(i - 1);
System.out.println(String.format("Fib#%1$d=%2$d", i, fib(i-1)));
}
}
private int fib(final int i) {
if (i == 0) {
return 0;
} else if (i == 1) {
return 1;
} else {
return fib(i - 2) + fib(i - 1);
}
}

How to Update a Counter for Fibonacci using Recursion?

Here's the deal I want to count the recursive calls for a basic Fibonacci code. I already have it so the values will print out in column format but I don't know how to update the recCounter. I think I have to add recCounter++; Somewhere and I don't know where
public static int recursionFibonacci(int n) {
recCounter = 1;
return fibonacci1(n);
}
public static int fibonacci1(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci1(n-1) + fibonacci1(n-2);
}
}
You should increment the counter every time you call the function:
public static int fibonacci1(int n) {
recCounter++; // <<-- here
if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci1(n-1) + fibonacci1(n-2);
}
}

Java sign of number code

I am trying to return the sign of a number using my code here but there seems to be a problem with my use of return? Help por favor?
import java.util.*;
public class ReturnTest {
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else if (n < 0)
return -1;
}
public static int sign(int n)
{
if (n > 0)
return 1;
else if (n < 0)
return -1;
return 0;
}
The last if-else was unnecessary. I've re-ordered to the 'usual' way of falling through at zero. Writing the code like this is shorter, cleaner and easier to understand
The problem is that you're not returning a method from all the paths in your method. You can see this by indenting the code accordingly based on Oracle Java Code Conventions:
public static int sign(int n) {
if (n > 0) {
return 1;
} else if (n == 0) {
return 0;
} else if (n < 0) {
return -1;
}
}
//needs a return here...
}
This can be fixed by having a default return value at the bottom. The code may look like:
public static int sign(int n) {
if (n > 0) {
return 1;
} else if (n == 0) {
return 0;
}
return -1;
}
There are other ways to implement this, but I prefer to do a fix based on your current implementation.
From your comments, looks like you're in your first steps to learn Java. To make an application, you need an entry point. This is marked by the main method which has this signature:
public static void main(String[] args)
So, in your current class, you can add this method and use it to call your sign method. I'll show a very basic sample:
public class ReturnTest {
public static int sign(int n) {
if (n > 0) {
return 1;
} else if (n == 0) {
return 0;
}
return -1;
}
public static void main(String[] args) {
int n = 10;
int signOfN = sign(n);
System.out.println("The sign of " + n + " is: " + signOfN);
}
}
It depends to you to adapt this code for your needs. I highly recommend you learn the basics. You can start here:
Trail: Learning the Java Language, Oracle tutorial about Java basic concepts.
Lesson: A Closer Look at the "Hello World!" Application, just to have a better understanding about the most basic application, the "Hello World!".
Spare the last if (if (n < 0)) because otherwise there is a theoretical branch where the function is never left!
Each branch must return!

Categories