This is my code for displaying factorial. But I think it's too long. How can I make my code shorter? Feedback will be appreciated. Thank you!
This is the sample output:
6! = 5*4*3*2*1 = 720
This is my code:
import java.io.*;
public class Factorial {
public static void main (String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int f = 1;
System.out.print("Enter number: ");
int num = Integer.parseInt(br.readLine());
int temp3 = num;
String temp [] = new String [num];
while (num >= 1)
{
f = num * f;
num = num - 1;
}
for (int x=1; x<temp3; x++)
{
temp[x]= "" + Integer.toString(x);
}
StringBuffer result = new StringBuffer();
for (int i = temp3 - 1; i >= 1; i--) {
result.append(temp[i]);
if (i > 1)
{
result.append("*");
}
}
System.out.print(temp3 + "! = " + result.toString() + " = " + f);
}
}
Rather than making your code shorter, focus on readability
Some things that you need to fix before making it shorter
Also try to write code yourself rather than copying snippets
for (int i = temp3 - 1; i >= 1; i--) {
result.append(temp[i]);
if (i > 1)
{
As far as I understand, there are 2 types of people in this world
How can you use both within a gap of 3 lines?