我应该创建一个程序,要求用户输入一个数字并采用该数字的阶乘,然后询问他们是否想要做另一个阶乘(Y,N)。Java阶乘输出
它应该像这样的工作:
- 输入号码采取的阶乘:4
- 4! = 24
- 做另一个阶乘(Y,N)? Ÿ 进入
- 重复,直到ň
我的输出是这样的:
- 输入号码采取的阶乘: “?另做阶乘(Y,N)”
4! = 1,无论我是否进入Y或N.
这里是我的代码:
import java.util.Scanner; public class factorial { public static void main (String [] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number you want to take the factorial of: "); int num = input.nextInt(); int fact = 1; System.out.printf("%d! = %d\n ", num, fact, Factorial(num, fact)); } public static int Factorial(int num, int fact) { Scanner input = new Scanner(System.in); char foo; System.out.print("Do another factorial (Y,N)?"); foo = input.next().charAt(0); for (int i = 1; i >= num; i++) { fact *= i; if (foo == 'Y') { System.out.print("Do another factorial (Y,N)?"); foo = input.next().charAt(0); continue; } else { break; } } return fact; } }
变更后:
import java.util.Scanner;
public class factorial
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number you want to take the factorial of: ");
int num = input.nextInt();
int fact = 1;
System.out.printf("%d! = %d\n ", num, Factorial(num, fact));
System.out.print("Do another factorial (Y,N)? ");
char foo = input.next().charAt(0);
while (foo != 'N')
{
System.out.print("Do another factorial (Y,N)? ");
foo = input.next().charAt(0);
System.out.print("Enter a number you want to take the factorial of: ");
num = input.nextInt();
System.out.printf("%d! = %d\n", num, Factorial(num, fact));
}
}
public static int Factorial(int num, int fact)
{
for (int i = 1; i <= num; i++)
{
fact *= i;
}
return fact;
}
}
输出仍存在一些问题:
- 输入一个数字以取阶乘:4
- 4! = 24
- 做另一个阶乘(Y,N)? Y
- 做另一个因子(Y,N)? Y
- 输入一个数字以取阶乘:4
- 4! = 24
- 做另一个阶乘(Y,N)? ñ
- 输入号码采取的阶乘:
我究竟将如何实现一个循环,检查用户是否输入Y或N,然后请求另一个号码的用户?我很抱歉,我对java很陌生。 – user1858350 2013-04-04 10:28:29
找出如何检查用户是否输入了Y或N,但是现在我遇到了用户输入Y后如何再次进行阶乘计算的问题 – user1858350 2013-04-04 10:37:40
@ user1858350您可能想要编辑您的问题,并将新代码单独发布“改变后”块。 – dasblinkenlight 2013-04-04 10:47:39