JAVA每日一练(1)

【程序1】
题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子对数为多少?

import java.util.Scanner;

/**
 * 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子对数为多少?
 * 分析 一月 1对, 2月 1对,3月 2对,4月 3对,5月5对,6月8对,7月13对,8月 21只
 */
public class Subject1 {

    public static void main(String[] args) {
        System.out.print("请输入你想知道的兔子数量的月份:");

        Scanner scanner=new Scanner(System.in);

        int n=scanner.nextInt();//获取输入的整数

        System.out.println(test(n));

        System.out.println(fun(n));

        scanner.close();
    }

    /**
     * 菜鸟写法
     * @param i
     * @return
     */
    public static int test(int i){
        int tot = 0;
        int a = 0;
        int b = 1;
        for(int j = 0;j<i; j++){
            tot = a+b;
            a = b;
            b = tot;
        }
        return a;
    }

    /**
     * 大神写法
     * @param
     * @return
     */
    private static int fun(int n){
        if(n==1 ||n==2)
            return 1;
        else
            return fun(n-1)+fun(n-2);
    }
}

运行结果:

【程序2】
题目:判断101-200之间有多少个素数,并输出所有素数。

/**
 * 【程序2】
 *  题目:判断101-200之间有多少个素数,并输出所有素数。
 *
 *  分析:什么是素数,不能被自己和1整除的数。
 */
public class Subject2 {
    public static void main(String[] args) {
        getPrimeNumber(101,200);
    }

    /**
     * 判断a和b之间有多少个素数
     * @param a
     * @param b
     */
    public static void getPrimeNumber(int a,int b){
        int sum = 0;
        if(a >= b){
            System.out.println("a不能大于等于b!");
        }
        System.out.print("素数:");
        for(int i=a;i<=b;i++){
            if(isPrimeNumber(i)){
                sum += 1;
                System.out.print(i+" ");
            }
        }
        System.out.println();
        System.out.println("存在素数数量:"+sum);
    }

    /**
     * 判断num是否是一个素数
     * @param i
     * @return
     */
    private static boolean isPrimeNumber(int i) {
        boolean flag = true;
        for(int j=2;j <= i/2;j++){
            if(i%j == 0){
                flag = false;
                break;
            }
        }
        return flag;
    }
}

运行结果:

java代码练习

【练习1】插入下面代码的缺失部分以输出“Hello World”。

public class MyClass { public static void main(String[] args) {    .   .
("Hello World"); } }

答案:

public class MyClass { public static void main(String[] args) { System.out.println
("Hello World"); } }

【练习2】Java 中的注释是用特殊字符编写的。 插入缺失的部分:


This is a single-line comment This is a multi-line comment 

答案:


//This is a single-line comment /*This is a multi-line comment */

猜你喜欢

转载自blog.csdn.net/m0_69824302/article/details/131619011