-2 java loops for-loop factorial
我的Java代码应该让用户输入一个数字,然后计算该数字的阶乘,我需要使用"for loop"当我输入数字5时,它告诉我,当它应该是120时,阶乘是6.我试图观察分解循环的教程,但它们不会工作,我认为它是因为我有"do"命令从调用中获取值
这是代码:
static Scanner kboard = new Scanner(System.in); //variable to read in values
public static void main(String[] args) {
int choice = 0;
String dummy = "";
String forename = "";
String surname = "";
int number = 0;
do {
System.out.println("1. display the user name, 2. calculate factorial, 3. exit");
choice = kboard.nextInt();
dummy = kboard.nextLine(); //strips out the return
if (choice == 1) {
forename = getforename();
surname = getsurname();
displaydetails(forename, surname);
}
if (choice == 2) {
number = getnumber();
calcfactorial(number);
}
if (choice == 3) {
System.out.println("bye");
}
} while (choice != 3);
}
public static String getforename() {
String newforename = "";
System.out.println("Please enter your forename ?");
newforename = kboard.next();
return (newforename);
} // end getforename
public static String getsurname() {
/*
Code to prompt the user to enter a surname
*/
String newsurname = "";
System.out.println("Please enter your surname ?");
newsurname = kboard.next();
return (newsurname);
} // end getsurname
public static void displaydetails(String displayforename, String displaysurname) {
/*
Code will carry out prescribed changes and display the result
*/
char displayinitial;
String displayusername = "";
displaysurname = displaysurname.toUpperCase();
displayinitial = displayforename.charAt(0);
displayusername = displayinitial + displaysurname;
System.out.println("Your username is " + displayusername);
}
public static int getnumber() {
System.out.println("What numbers factorial do you want to know?");
int newnumber = kboard.nextInt();
return newnumber;
}
public static void calcfactorial(int newnumber) {
int count = 0;
int factorial = 1;
if (newnumber > 0) {
for (count = 1; count <= newnumber; count++); {
factorial = factorial * count;
System.out.println("Factorial of " + newnumber + " is: " + factorial);
}
} else {
System.out.println("Number must be positive");
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用过调试器,那么您可以告诉它只在calcfactorial方法中执行一次乘法,并且count已经6在此时.原因:
首先,在for条件循环结束时删除分号.它充当for循环的主体.这count等于newnumber + 1,或6.
其次,在for循环结束后移动print语句,但仍在if块内.否则你会得到newnumber打印输出.
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |