【发布时间】:2017-02-06 04:00:06
【问题描述】:
我正在使这个程序能够计算阶乘。如果他们输入超过 20 的值,我需要它说一句话,但我已经创建了无限循环。我的台词说
System.out.print ("ERROR: The result is inaccurate because the number was too large for the data type");}
是一个无限循环。我似乎无法弄清楚如何解决它。我试过移动东西的位置,但我无法弄清楚。任何帮助表示赞赏。
import java.util.Scanner;
import java.text.NumberFormat;
public class FactoralApp
{
public static void main(String[] arge)
{
//Welcome users the the application and get user input
System.out.print("Welcome to the Factoral Calculator" + "\n");
int num;
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) { //set up the while loop so that users can find many factorials
long factorial=1; //initialize variables
System.out.print("\n" + "Enter an integer between 1 and 20: "); //promt users for input
num = sc.nextInt();
for (int i = num; i >= 1; i--){ //Calculate factorial
factorial = factorial * i;}
while (num > 20) {
System.out.print ("ERROR: The result is inaccurate because the number was too large for the data type");}
// Format and display the results
NumberFormat number = NumberFormat.getNumberInstance();
String message =
("\n" + "The factoral of " + num + " is " + number.format(factorial) + "." + "\n"); //create message
System.out.println(message); // Output the formated message
System.out.print ("Continue (y/n): "); //promt users for input
choice = sc.next();
} // End While
} // End main ()
} // End Class
【问题讨论】:
-
解决问题的第一步是隔离问题,这意味着是时候进行一些认真的调试了,或者使用允许您单步调试代码并分析变量作为程序进度,或者使用记录器,或者使用“穷人的调试器”——许多 println 语句在程序进行时暴露变量状态。祝你好运!
-
您是不是要使用
if而不是while? -
您在 while 布尔条件中检查什么变量?下一步——您是否 在 while 循环中的任何位置更改变量?否则,如果您从不更改循环内的 num,则 while 循环的布尔测试结果将从不更改,并且循环将永远不会结束。这不是一个编程问题,而是一个简单的逻辑问题。
-
调试,尝试打印出变量,这样你就可以看到它是如何改变它的循环。
-
感谢 PM 77-1 将其设置为 if 而不是修复它。