java实现阶乘的计算,抛出异常不会,怎么使用标号跳转,需要帮解决一下
2016-04-21 19:58
716 查看
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | import java.util.*;public class jiechen15{//计算一个整数阶乘类 private static final int A=15;//定义常量A private static final int B=11;//定义常量B //For循环计算阶乘 public static int simpleCircle(int num){ int sum=1; if(num<0){//判断传入数是否为负数 System.out.println("please enter a negative number!");//抛出不合理参数异常 break flag;//跳回标记、、、不能跳啊 帮解决一下 } for(int i=1;i<=num;i++){ sum *= i;//每循环一次进行乘法运算 } return sum;//返回阶乘的值 } //递归计算阶乘 public static int reCircle(int num){ int sum=1; if(num<0){ System.out.println("please enter a negative number!"); return 0; break flag;//跳回标记、、、不能跳啊 帮解决一下 } if(num==0) return 1;//0!=1 if(num==1) return 1; else { sum=num*reCircle(num-1);//递归 return sum; } } //程序入口public static void main(String[] args){ int m=1;//控制do-while语句 System.out.println("For循环计算常量"+A+"的阶乘为:"+simpleCircle(A));//for循环计算常量A的阶乘 System.out.println("递归计算常量"+B+"的阶乘为"+reCircle(B)); do{ System.out.println("please choose function:"); System.out.println("1.For循环 "); System.out.println("2.递归"); System.out.println("0.退出"); Scanner sc=new Scanner(System.in); flag://标号 System.out.print("please enter a number to caculate:"); int i=sc.nextInt(); System.out.print("choose method to caculate:"); int c=sc.nextInt(); switch(c){ case 1:System.out.println("For循环计算"+i+"的阶乘为:"+simpleCircle(i));//调用For循环算法 break; case 2:System.out.println("递归计算"+i+"的阶乘为:"+reCircle(i));//调用递归算法 break; case 0: System.out.println("Wherecom to use!"); m=0; } }while(m==1); }} |
相关文章推荐
- 趣味整数-3位反序数-java
- Eclipse取得路径的方法
- SSH:Struts has detected an unhandled exception
- 快速构建Spring boot项目(功能是检测访问页面的设备)
- Struts2中namespace的用法
- struts --interceptor
- 如何在Eclipse中查看JDK类库的源代码 【转】
- Eclipse将输出结果保存到文件中
- Java urlrewrite+Maven 简单使用
- Java Calendar 基础详解实例
- struts--Action解读
- HashMap内部实现原理
- java并发之Lock与synchronized的区别
- Java加密技术(一)——BASE64与单向加密算法MD5&SHA&MAC
- Spark-submit 时出现java.lang.ClassNotFoundException
- java容器学习
- java 链表 树
- java并发之Lock
- Java读取properties文件中文乱码问题解决
- struts2动态方法调用