遇一山,过一山,处处有风景;只要勇敢向前,一路尽是繁花盛开。 | (点击查看→)【测试干货】python/java自动化、持续集成、性能、测开、简历、笔试面试等

【参考答案】java基础练习:方法、递归

方法实现

定义方法(不用jdk提供的方法),计算x的y次方,如2的5次方

package com.qzcsbj;


/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
public class Test {
    public static void main(String[] args) {
        System.out.println(calc(2, 5));
        System.out.println(calc(2, 0));
    }
    public static int calc(int x, int y) {
        if (y == 0) {
            return 1;
        }
        int result = x;
        for (int i = 1; i < y; i++) {
            result = result * x;
        }
        return result;
    }
}

  

猜数字游戏:随机生成[0,100]之间的随机数,让用户猜生成的数字,显示猜大了、猜小了,如果猜对了,提示共猜了多少次。

用Math.random()方法

package com.qzcsbj;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        int x = (int) (Math.random() * 101);
        System.out.println(x);
        Scanner input = new Scanner(System.in);

        int count = 0;
        while (true) {
            count++;
            System.out.print("请输入您要猜的数字:");
            int guess = input.nextInt();
            if (guess > x) {
                System.out.println("猜大了");
            }
            if (guess < x) {
                System.out.println("猜小了");
            }
            if (guess == x) {
                System.out.println("恭喜您,猜对了,共猜了:" + count + "次");
                break;
            }
        }
    }
}

  

 

递归实现

计算x的y次方,如2的5次方

package com.qzcsbj;


public class Test {
    public static void main(String[] args) {
        System.out.println(calc(2, 5));
        System.out.println(calc(2, 0));
    }

    public static int calc(int x, int y) {

        if (y == 0) {
            return 1;
        }
        return x * calc(x, y - 1);
    }
}

 

输出n(n=5)到0的整数

package com.qzcsbj;

import java.util.Scanner;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
public class Test {
    public static void main(String[] args) {
        t(5);
    }

    public static void t(int n){
        System.out.println(n);
        if(n<1){
            return;
        }
        t(n-1);
    }
}

 

 

 

 

【java百题计划汇总】

详见:https://www.cnblogs.com/uncleyong/p/15828510.html

 

【bak】

原文会持续更新,原文地址: https://www.cnblogs.com/uncleyong/p/17043952.html

 

posted @ 2023-01-12 07:47  全栈测试笔记  阅读(232)  评论(2编辑  收藏  举报
浏览器标题切换
浏览器标题切换end