Hey Everyone,
I'm new to JCreator and trying to compile this program, however I keep getting "missing return statement"...please help.

import javax.swing.JOptionPane;
public class DoCount {

    public static void main(String[] args) {
    String nString=JOptionPane.showInputDialog("Enter n:");
    int n = Integer.parseInt(nString);
    factorial(n);
}
    public static int factorial(int n){
    int count = n;
        if (n < 0){
    System.out.println("exit");
    }

    else if (n == 0){
    System.out.println("n==0");
    }

    else{
    while(count>0){
    n=n*(count-1);
}
return n;
}
}
}

Edited 3 Years Ago by Dani: Formatting fixed

The error says it all the factorial method is missing a return statement
the return n should be outside of the else statement or maybe put one before the ending bracket of the method

Edited 4 Years Ago by zeroliken: n/a

Hey Everyone,
I'm new to JCreator and trying to compile this program, however I keep getting "missing return statement"...please help.


import javax.swing.JOptionPane;
public class DoCount {

public static void main(String[] args) {
String nString=JOptionPane.showInputDialog("Enter n:");
int n = Integer.parseInt(nString);
factorial(n);
}
public static int factorial(int n){
int count = n;
if (n < 0){
System.out.println("exit");
}

else if (n == 0){
System.out.println("n==0");
}

else{
while(count>0){
n=n*(count-1);
}
return n;
}
}
}

This will work for you:

import javax.swing.JOptionPane;
public class DoCount {

public static void main(String[] args) {
String nString=JOptionPane.showInputDialog("Enter n:");
int n = Integer.parseInt(nString);
factorial(n);
}
public static int factorial(int n){
int count = n;
if (n < 0){
System.out.println("exit");
}

else if (n == 0){
System.out.println("n is :0");
}

else{
while(count>0){
n=n*(count-1);

// System.out.println("null ");
}

}
return n;
}
}
Comments
Zeroliken already told him this.

When posting code please put it in code tags to preserve the formatting. Use the (CODE) icon above the input box.

Your unformatted code is harder to read and understand.

Edited 3 Years Ago by mike_2000_17: Fixed formatting

Comments
no idea why this should be negative

Since you're doing a System.out with your other use cases, why not drop a return all together and just do a System.out? This also allows you to drop the n==0 code as well, since the last condition will account for it.

public static void factorial(int n) {

		if (n < 0)
			System.out.println("exit");
		
		else  {
			int count = n;
			while (count > 0)
				n *= --count;
			System.out.println(new StringBuilder("n==").append(n).toString());
		}
		
	}

Edited 4 Years Ago by ztini: n/a

This article has been dead for over six months. Start a new discussion instead.