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;
}
}
}

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

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;
}
}
commented: Zeroliken already told him this. -3

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.

commented: no idea why this should be negative +15
Member Avatar for ztini

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());
		}
		
	}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.