我應該創建一個程序,要求用戶輸入一個數字並採用該數字的階乘,然後詢問他們是否想要做另一個階乘(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