小编mor*_*apg的帖子

为什么我的catch块会永远循环?

我正在做一个计算阶乘的程序,我写了一个捕获NumberFormatException和InputMismatchException的循环.NumberFormatException运行正常并循环回try块,但InputMismatchException反复显示其消息而不循环回try块.我不确定我做错了什么.这是我的代码:

import java.util.*;

public class Factorial 
{
public static void main(String[] args) 
{
    Scanner s = new Scanner(System.in);
    System.out.println("Factorial Test Program\n");

    boolean success = false;

    while (!success)
    {   
        try
        {
            System.out.print("Enter an integer number: ");
            int number = s.nextInt();

            if (number < 0) throw new NumberFormatException();

            long f = number;

            for (int i = number-1; i>0; i--)
                f *= i;

            if (number==0) f=1;

            System.out.printf("The factorial of %s is %s.\n", number, f);
            success=true;

            System.out.println("Done!");
        }
        catch (NumberFormatException e)
        {
            System.out.println("Factorial of …
Run Code Online (Sandbox Code Playgroud)

java exception-handling try-catch while-loop

2
推荐指数
1
解决办法
752
查看次数

标签 统计

exception-handling ×1

java ×1

try-catch ×1

while-loop ×1