0

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 by Dani: Formatting fixed

5
Contributors
4
Replies
5
Views
4 Years
Discussion Span
Last Post by ztini
0

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 by zeroliken: n/a

-2

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.
0

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 by mike_2000_17: Fixed formatting

Comments
no idea why this should be negative
0

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 by ztini: n/a

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.