Java基础:代码小作业(四)

1、斐波那契数列

斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
89, 144, 233,377,610,987,1597,2584,……
:在斐波那契数列中第 n 个数字是多少?
注意:第1个是0,第2个是第一个1,第3个开始,每一项都等于前两个之和。

import java.util.Scanner;

/**
 * @author Hui
 */
public class Fibonacci{
    public long fibonacci(int n){
        // 判断为第一个和第二个时。
        if (n == 1 || n == 0){
            return n;
        }
        // 因为第n个总是(n-1)个与(n-2)个的和,所以使用递归。
        return fibonacci(n-1) + fibonacci(n-2);
    }
    public static void main(String[] args) {
        Fibonacci fibonacci = new Fibonacci();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入:");
        int n = scanner.nextInt();
        // 得到第n个斐波那契数
        long numb = fibonacci.fibonacci(n);
        System.out.println("第" + n + "个斐波那契数是:" + numb);
    }
}

2、阶乘

:n的阶乘。
举例
5的阶乘
= 4的阶乘 * 5
= 3的阶乘 * 4 * 5
= 2的阶乘 * 3 * 4 * 5
= 1 * 2 * 3 * 4 * 5
代码

import java.util.Scanner;

/**
 * @author Hui
 */
public class Factorial {
    public int factorial(int n){
        if (n <= 1){
            return 1;
        }
        return n * factorial(n-1);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Factorial factorial = new Factorial();
        System.out.println("请输入数字:");
        int n = scanner.nextInt();
        System.out.println("阶乘为:" + factorial.factorial(n));
    }
}

3、统计某单词个数:

查找某个单词在文章中出现的次数。

/**
 * @author Hui
 */
public class WordCount {
    public int count(String article,String word){
        int count = 0;
        // 遇到【!._,'@?空格】分割单词
        String[] strings = article.split("[!._,'@? ]");
        for (String string : strings) {
        // 不区分单词大小写比较单词,区分的话使用equal()
            if (string.equalsIgnoreCase(word)){
                count += 1;
            }
        }
        return count;
    }
    public static void main(String[] args) {
        WordCount wordCount = new WordCount();
        String article = "Hello world! Hello jerry. Hello Tom!";
        int count = wordCount.count(article,"world");
        System.out.println(count);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值