简单因子程序中的错误

时间:2015-02-14 12:34:24

标签: java



//WAP to find the factorial of a number using recursion.

import java.io.*;

class Factorial
{
      public static int Fact(int n)
      {
         if(n!=1)
             return n*Fact(n-1);
      }
      public static void main(String []args)
      {
            int n;
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter a number to find its factorial=");
            String s=br.readLine();
            n=Integer.parseInt(s);
            n=Fact(n);
            System.out.print("The Factorial is "+n);
       }
}




我在这里做的错误是什么?它在编译时显示2个错误 1.声明丢失 2.必须抓获或宣布未报告的例外情况......

2 个答案:

答案 0 :(得分:1)

您希望捕获IOException方法可能引发的readLine(),并且您必须在n==1时返回一些内容。在这种情况下只需return 1;(因为1的阶乘是1)。所以这就是你想要的:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Factorial {
    public static int Fact(int n) {
        if (n != 1)
            return n * Fact(n - 1);
        return 1;
    }

    public static void main(String[] args) {
        try {
            int n;
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    System.in));
            System.out.println("Enter a number to find its factorial=");
            String s = br.readLine();
            n = Integer.parseInt(s);
            n = Fact(n);
            System.out.print("The Factorial is " + n);
        } catch (IOException e) {
            // bla
        }
    }
}

答案 1 :(得分:0)

两个人认为:

首先:如果n == 1,你不会在'public static int Fact(int n)`中返回一个值

 public static int Fact(int n)
 {
    if(n!=1)
        return n*Fact(n-1);
    return 1;
 }

第二:br.readLine();抛出IOException。必须在方法Header中声明它,或者必须捕获它。

 public static void main(String []args) throws IOException
 {
       int n;
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       System.out.println("Enter a number to find its factorial=");
       String s=br.readLine();
       n=Integer.parseInt(s);
       n=Fact(n);
       System.out.print("The Factorial is "+n);
  }

}