JavaSE02、方法,递归迭代

一、输入输出

第一种方式:

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) throws IOException {
        System.out.print("Enter a Char:");
        char i = (char)System.in.read(); // Alt+回车
        System.out.println("your char is :"+i);
    }
}

第二种方式:

1.如果有整数和字符串同时读,先读取字符串
2.next–>不能读取空格
–> nextLine–>读取包括空格

import java.util.Scanner;

public class TestDemo {
	public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // 从键盘读
        int n = scanner.nextInt();
        System.out.println(n);

        /* double d = scanner.nextDouble();
        System.out.println(d); */

        // 放在n前面读才可以 回车
        String str1 = scanner.nextLine();
        System.out.println(str1);

        // next不能读空格
        String str2 = scanner.nextLine();

        // 关闭
        scanner.close();
    }
}

循环读取n个数字

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) { // 结束:Ctrl+d
            int n = scanner.nextInt();
            System.out.println(n);
        }
    }
}


二、方法

方法:C的函数 --> 功能 可以重复使用的
public static 返回值 方法名称(形参列表) {
函数体; // 方法体
}

1、求1-10的和**

public class TestDemo {
	 /**
     * 求1-n的和
     * 函数名字:小驼峰
     * @param n 输入的数字
     * @return 求的和
     */
    public static int sumAdd(int n) {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return sum;
    }
    
    public static void main(String[] args) {
		int ret = sumAdd(10); // 方法的调用
        System.out.println(ret);
    }
}

2、注意问题

public class TestDemo {
	 
    public static int sumAdd(int n) {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return sum;
    }
   
    >1. java 没有“函数声明”的概念
	>2. 方法的定义必须在类之中,代码书写在调用位置的上方或下方均可
	>3. 函数开辟的内存--栈帧
	>4. 每个函数在调用的时候,都会开辟栈帧,属于这个函数的内存
   
    public static void main(String[] args) {
		// System.out.println(func()); // err

        System.out.println(sumAdd(10)*2); // 函数的返回值支持链式调用
    }

    public static void func() {

    }
}

在这里插入图片描述


3、计算1!+2!+3!+4!+5!

public class TestDemo {
    public static int fac(int n) {
        int ret = 1;
        for (int i = 1; i <= n; i++) {
            ret *= i;
        }
        return ret;
    }
    
    /**
     * 求n的阶乘的和
     * 阅读性提高了
     * @param n
     * @return
     */
    public static int facSum(int n) {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += fac(i);
        }
        return sum;
    }
    
    public static void main(String[] args) {
		System.out.println(facSum(5));
    }
}

4、形参和实参

public class TestDemo {
	public static void swap(int a, int b) {
        // java里,拿不到栈上的地址
        // 如果要实现交换,只能把a,b放到堆上
        int tmp = a;
        a = b;
        b = tmp;
    }
    
    public static void main(String[] args) {
		int a = 10;
        int b = 20;
        System.out.println("交换前:"+a+" "+b);
        swap(a, b);
        System.out.println("交换后:"+a+" "+b);
    }
}

5、方法的重载 overload

重载的规则:
可以不是一个类(继承关系上也可以)
1. 方法名相同
2. 方法的参数列表不同(个数或者参数类型)
3. 方法的返回值类型不影响重载

例:add 求两个整数和,两个小数和,三个整数和

public class TestDemo {
	public static int add(int a, int b) {
        return a + b;
    }
    public static double add(double a, double b) {
        return a + b;
    }
    public static int add(int a, int b, int c) {
        return a + b + c;
    }
}

6、模拟用户输入密码

import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

public class TestDemo {
    public static void login() {
        Scanner scanner = new Scanner(System.in);
        int count = 3;
        while(count != 0) {
            System.out.println("请输入你的密码:");
            String password = scanner.nextLine();
            if(password.equals("12345")) {
                System.out.println("登录成功!");
                break;
            } else {
                count--;
                System.out.println("密码错误,你还有 "+count+"次机会!");
            }
        }
    }

    public static void main(String[] args) {
        // 模拟用户输入密码
        login();
    }
}

7、递归

递归:方法 自己调用自己的过程

  1. 有一个趋向于终止的条件
  2. 自己调用自己
7.1、求n的阶乘
public class TestDemo {

    public static int fac(int n) {
        if(n == 1) {
            return 1;
        }
        int tmp = n * fac(n-1);
        return tmp;
    }

	public static void main(String[] args) {
        System.out.println(fac(5));
    }
}

7.2、求n的和

sumAdd(10) --> 1+2+3+…+10

public class TestDemo {

    public static int sumAdd(int n) {
        if(n == 1) {
            return 1;
        } else {
            return n + sumAdd(n-1);
        }
    }

	public static void main(String[] args) {
        int sum = sumAdd(3);
        System.out.println(sum);
    }
}

7.3、顺序打印每一位
public class TestDemo {
	public static void printNum(int n) {
        if(n < 10) {
            System.out.print(n%10+" ");
        }else {
            printNum(n/10);
            System.out.print(n%10+" ");
        }
    }

	public static void main(String[] args) {
        printNum(123);
    }
}

7.4、返回每位之和 1234–>1+2+3+4
public class TestDemo {
	public static int sumEveryNum(int n) {
        if(n < 10) {
            return n;
        }else {
            return n % 10 + sumEveryNum(n/10);
        }
    }

	public static void main(String[] args) {
        System.out.println(sumEveryNum(1725));
    }
}

7.5、斐波那契数
public class TestDemo {
	public static int fib(int n) {
        // 递归
        if(n == 1 || n == 2) {
            return 1;
        }else {
            return fib(n-1) + fib(n-2);
        }
    }

    public static int fib2(int n) {
        // 循环/迭代
        if(n == 1 || n == 2) {
            return 1;
        }
        int f1 = 1;
        int f2 = 1;
        int f3 = 0;
        for (int i = 3; i <= n; i++) {
            f3 = f1 + f2;
            f1 = f2;
            f2 = f3;
        }
        return f3;
    }

	public static void main(String[] args) {
        System.out.println(fib(10));

        System.out.println(fib2(50));
    }
}

7.6、青蛙跳台阶
public class TestDemo {
	public static int frogJump(int n) {
        // 递归
        if(n == 1 || n == 2) {
            return n;
        }else {
            return frogJump(n-1) + frogJump(n-2);
        }
    }

    public static int frogJump2(int n) {
        // 迭代
        if(n == 1 || n == 2) {
            return n;
        }
        int f1 = 1;
        int f2 = 2;
        int f3 = 0;
        for (int i = 3; i <= n; i++) {
            f3 = f1 + f2;
            f1 = f2;
            f2 = f3;
        }
        return f3;
    }
    
	public static void main(String[] args) {
        System.out.println(frogJump(1));
        System.out.println(frogJump(2));
        System.out.println(frogJump(3));
        System.out.println(frogJump(4));

        System.out.println(frogJump2(1));
        System.out.println(frogJump2(2));
        System.out.println(frogJump2(3));
        System.out.println(frogJump2(4));
    }
}

7.7、递归求解汉诺塔问题
public class TestDemo {

    public static void move(char pos1, char pos2) {
        System.out.print(pos1+"->"+pos2+" ");
    }

    /**
     *
     * @param n 盘子个数
     * @param pos1 盘子所在起始位置
     * @param pos2 盘子的中转位置
     * @param pos3 盘子的结束位置
     */
    public static void hanio(int n, char pos1, char pos2, char pos3) {
        if(n == 1) {
            move(pos1, pos3); // A-C
        }else {
            hanio(n-1, pos1, pos3, pos2);
            move(pos1, pos3);
            hanio(n-1, pos2, pos1, pos3);
        }
    }

    public static void main1(String[] args) {
        // 汉诺塔
        // 1: A->C  1
        // 2: A->B  A->C  B->C  3
        // 3: A->C  A->B  C->B  A->C  B->A  B->C  A->C  7
        // 64:       2^N -1
        hanio(1, 'A', 'B', 'C');
        System.out.println();
        hanio(2, 'A', 'B', 'C');
        System.out.println();
        hanio(3, 'A', 'B', 'C');
        System.out.println();
    }

}


三、编程题

1、猜数字游戏

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
        Random random = new Random();
        int rand = random.nextInt(100);
        Scanner scanner = new Scanner(System.in);
        while(true) {
            System.out.print("请输入你要猜的数字:");
            int n = scanner.nextInt();
            if (n < rand) {
                System.out.println("猜小了");
            } else if (n == rand) {
                System.out.println("猜对了");
                break;
            } else {
                System.out.println("猜大了");
            }
        }
}

2、判断素数

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
		// 给定一个数字,判定一个数字是否是素数
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        int i = 0;
        for (i = 2; i < num; i++) {
            if(num % i == 0) {
                System.out.println(num+"num不是素数!");
                break;
            }
        }
        if(i == num) {
            System.out.println("num是素数");
        }
    }
}

优化1:

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
		// n --> a*b  例16  1*16  2*8  4*4  其中一定有一个数字是小于等于16/2 --8
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        int i = 0;
        for (i = 2; i <= num / 2; i++) { //
            if(num % i == 0) {
                System.out.println(num+"num不是素数!");
                break;
            }
        }
        if(i > num / 2) { //
            System.out.println("num是素数");
        }
    }
}

优化2:

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
		// n --> a*b  例16  1*16  2*8  4*4  其中一定有一个数字是小于等于根号n --4
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        int i = 0;
        for (i = 2; i <= Math.sqrt(num); i++) { //
            if(num % i == 0) {
                System.out.println(num+"num不是素数!");
                break;
            }
        }
        if(i > Math.sqrt(num)) { //
            System.out.println("num是素数");
        }
    }
}

3、输出9*9乘法口诀表

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
		for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(i+"*"+j+"="+i*j+" ");
            }
            System.out.println();
        }
    }
}

4、求两个正整数的最大公约数

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
  	    // 辗转相除法
		int a = 24;
        int b = 18;
        int c = a % b; // 24 % 18 = 6
        while(c != 0) {
            a = b;
            b = c;
            c = a % b;
        }
        System.out.println("最大公约数是"+b);
    }
}

5、计算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
		double sum = 0.0;
        int flag = 1;
        for (int i = 1; i <= 100; i++) {
            sum += (1.0 / i) * flag;
            flag = -flag;
        }
        System.out.println(sum); // 0.688172179310195
    }
}

6、1到 100 的所有整数中出现多少个数字9

import java.util.Scanner;

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
		int count = 0;
        for(int i = 1; i <= 100; i++) {
            if(i % 10 == 9) {
                count++;
            }
            if(i / 10 == 9) {
                count++;
            }
        }
        System.out.println(count);
    }
}

7、水仙花数

public class TestDemo {
    public static void findNum(int n) {
        for (int i = 1; i <= n; i++) {
            int count = 0; // 计算数字的位数
            int tmp = i;
            while(tmp != 0) {
                count++;
                tmp /= 10;
            }
            tmp = i;
            int sum = 0;
            while(tmp != 0) {
                sum += Math.pow(tmp %  10, count);
                tmp /= 10;
            }
            if(sum == i) {
                System.out.println(i);
            }
        }
    }
	
	public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt(); // 999999
        findNum(n);
	}
}

8、二进制位有多少1

public class TestDemo {
    public static int numOfOne(int n) {
        // 二进制位有多少1
        int count = 0;
        while (n != 0) {
            if ((n & 1) == 1) {
                count++;
            }
            n = n >>> 1; // 无符号右移
        }
        return count;
    }
	
    public static int numOfOne2(int n) {
        int count = 0;
        while (n != 0) {
            count++;
            n = n & (n - 1);
        }
        return count;
    }
    
	public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        
        System.out.println(numOfOne(n));
	}
}

9、获取奇偶数位,分别输出

public class TestDemo {

    public static void printBinary(int n) {
        for (int i = 30; i >= 0; i-=2) {
            System.out.print(((n >> i) & 1)+" ");
        }
        System.out.println();
        for (int i = 31; i >= 1; i-=2) {
            System.out.print(((n >> i) & 1)+" ");
        }
    }

	public static void main(String[] args) {
        printBinary(15);
    }
}

10、逆序打印

public class TestDemo {

    public static void printNum(int n) {
        while(n != 0) {
            System.out.print(n%10+" ");
            n /= 10;
        }
    }

	public static void main(String[] args) {
        printNum(123);
    }
}

11、有一组数据,只有一个数字是出现一次,其他是两次,请找出这个数字

public class TestDemo {

	public static void main(String[] args) {
        int[] array = {1, 2, 3, 2, 1};
        // int sum = 0;
        int sum = array[0];
        for (int i = 1; i < array.length; i++) {
            sum = sum ^ array[i];
        }
        System.out.println(sum);
    }
}

12、调整数组顺序使得奇数位于偶数之前。调整之后,不关心大小顺序

public class TestDemo {

	public static void main(String[] args) {
        int[] array = {1,2,3,4,5,6,7,8,9,10};
        int left = 0;
        int right = array.length-1;

        while(left < right) {
            while(left < right && array[left] % 2 == 0) {
                left++;
            }
            while(left < right && array[right] % 2 != 0) {
                right--;
            }
            int tmp = array[left];
            array[left] = array[right];
            array[right] = tmp;
        }

        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]+" ");
        }
    }
}

13、X形图案

描述
KiKi学习了循环,BoBo老师给他出了一系列打印图案的练习,该任务是打印用“*”组成的X形图案。
输入描述:
多组输入,一个整数(2~20),表示输出的行数,也表示组成“X”的反斜线和正斜线的长度。
输出描述:
针对每行输入,输出用“*”组成的X形图案。

/*import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNext()) {
            int n = scanner.nextInt();
            int i = 0;
            for(i = 0; i< n; i++) {
                int j = 0;
                for(j=0; j<n; j++) {
                    if(j == i || j + i == n - 1) {
                        System.out.print("*");
                    }
                    else {
                        System.out.print(" ");
                    }
                }
                System.out.println();
            }
        }
    }
}*/

import java.util.*;

public class Main {
    
    public static void func(int n) {
        for(int i = 0; i< n; i++) {
            for(int j=0; j<n; j++) {
                if(j == i || j + i == n - 1) {
                    System.out.print("*");
                 }else {
                    System.out.print(" ");
                 }
            }
            System.out.println();
         }
    }
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while(scan.hasNextInt()) {
            int n = scan.nextInt();
            func(n);
        }
    }
}

14、求最大值

创建方法求两个数的最大值max2,随后再写一个求3个数的最大值的函数max3。

​ 要求:在max3这个函数中,调用max2函数,来实现3个数的最大值计算

import java.util.Random;
import java.util.Scanner;

public class TestDemo {

    /**
     * @param a
     * @param b
     * @return
     */public static int max2(int a, int b) {
        return a > b ? a : b;
    }
    public static int max3(int a, int b, int c) {
        int max = max2(a, b);
        max = max2(max, c);
        return max;
    }

    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 20;
        int num3 = 30;
        int maxAB = max2(num1, num2);
        System.out.println("max->num1 num2: "+maxAB);

        int maxABC = max3(num1, num2, num3);
        System.out.println("max->num1 num2 num3: "+maxABC);
    }
}

15、求最大值方法的重载

在同一个类中定义多个方法:要求不仅可以求两个整数的最大值,还可以求两个小数的最大值,以及两个小数和一个整数的大小关系

public static TestDemo {
        
    public static int maxN(int x, int y) {
        return x > y ? x : y;
    }

    public static double maxN(double x, double y) {
        return x > y ? x : y;
    }

    public static void maxN(int x, double y, double z) {
        double tmp =  x > y ? x : y; // x y --> maxdouble max = tmp > z ? tmp : z;
        double tmp2 = x < y ? x : y;
        double min = tmp2 < z ? tmp2 : z;
        double mid = (x*1.0 + y + z) - max - min;
        System.out.println(max+">"+mid+">"+min);

    }

    public static void main(String[] args) {
        System.out.println(maxN(10, 20));
        System.out.println(maxN(2.7, 5.8));
        maxN(3, 2.1, 3.7);
    }

}
  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 24
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三春去后诸芳尽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值