JavaSE02、方法,递归迭代
- 一、输入输出
- 第一种方式:
- 第二种方式:
- 循环读取n个数字
- 二、方法
- 1、求1-10的和**
- 2、注意问题
- 3、计算1!+2!+3!+4!+5!
- 4、形参和实参
- 5、方法的重载 overload
- 6、模拟用户输入密码
- 7、递归
- 7.1、求n的阶乘
- 7.2、求n的和
- 7.3、顺序打印每一位
- 7.4、返回每位之和 1234-->1+2+3+4
- 7.5、斐波那契数
- 7.6、青蛙跳台阶
- 7.7、递归求解汉诺塔问题
- 三、编程题
- 1、猜数字游戏
- 2、判断素数
- 3、输出9*9乘法口诀表
- 4、求两个正整数的最大公约数
- 5、计算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值
- 6、1到 100 的所有整数中出现多少个数字9
- 7、水仙花数
- 8、二进制位有多少1
- 9、获取奇偶数位,分别输出
- 10、逆序打印
- 11、有一组数据,只有一个数字是出现一次,其他是两次,请找出这个数字
- 12、调整数组顺序使得奇数位于偶数之前。调整之后,不关心大小顺序
- 13、X形图案
- 14、求最大值
- 15、求最大值方法的重载
一、输入输出
第一种方式:
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+dint 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()); // errSystem.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、递归
递归:方法 自己调用自己的过程
- 有一个趋向于终止的条件
- 自己调用自己
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 -1hanio(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 --8Scanner 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 --4Scanner 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 = 6while(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(); // 999999findNum(n);}
}
8、二进制位有多少1
public class TestDemo {public static int numOfOne(int n) {// 二进制位有多少1int 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);}}
JavaSE02、方法,递归迭代相关推荐
- [Leedcode][JAVA][第94/144/145题][前中后序遍历][递归][迭代][二叉树]
[问题描述][] 前序遍历 先输出当前结点的数据,再依次遍历输出左结点和右结点 中序遍历 先遍历输出左结点,再输出当前结点的数据,再遍历输出右结点 后续遍历 先遍历输出左结点,再遍历输出右结点,最后输 ...
- [递归|迭代] leetcode 21 合并两个有序链表
[递归|迭代] leetcode 21 合并两个有序链表 1.题目 题目链接 将两个升序链表合并为一个新的升序链表并返回.新链表是通过拼接给定的两个链表的所有节点组成的. 示例: 输入:1->2 ...
- 二叉树的中序遍历 [递归 迭代]
中序遍历的递归 & 迭代 前言 一.二叉树的中序遍历 二.递归 & 迭代 1.递归版 2.迭代(断左子树版) 3.迭代(root迭代版) 4.mirror(O(1)空间版) 总结 参考 ...
- Java 二叉树基础概念(递归迭代)
目录 1. 树型结构 1.1概念 1.2 概念(重要) 2. 二叉树(重点) 2.1 概念 2.2 二叉树的基本形态 2.3 两种特殊的二叉树 2.4 二叉树的性质 a.满二叉树 b.完全二叉树 2. ...
- java中的方法递归
JAVA中的方法递归 递归的思路 代码举例 一.递归的思路 一个方法在执行时,调用自身被称为"递归". 递归相当于数学归纳法,有一个起始条件,有一个递推公式. 递归可以分为:单路递 ...
- java-青蛙跳台阶问题(递归,迭代)
题目一 一只青蛙一次可以跳上1级台阶,也可以跳上2级.求该青蛙跳上一个n级的台阶总共需要多少种跳法 方法一,用递归 思路 如果只有一级台阶, 一种跳法 如果两级台阶,两种跳法,① 每次跳一级 ② 一次 ...
- JAVA入门级教学之(方法递归)
目录 JAVA入门级教学之(方法递归) 1.关于方法的递归调用: 2.递归是很耗费栈内存的,递归算法可以不用的时候尽量别用 3.以下程序运行的时候发生了这样的一个错误[不是异常,是错误] 4.递归必须 ...
- 在Java 8中,有没有一种简洁的方法可以迭代带有索引的流?
本文翻译自:Is there a concise way to iterate over a stream with indices in Java 8? Is there a concise way ...
- JS高程5.引用类型(6)Array类型的位置方法,迭代方法,归并方法
一.位置方法 ECMAScript5为数组实例添加了两个位置:indexOf()和 lastIndexOf().这两个方法接收两个参数:要查找的项和(可选的)表示查找起点位置的索引(如在数组[7,8, ...
- php 遍历html节点,JavaScript_js获取html页面节点方法(递归方式),很久没有操作过递归调用了。 - phpStudy...
js获取html页面节点方法(递归方式) 很久没有操作过递归调用了.看完之后,蓦然惊醒啊! 统计Element节点 var elementName=""; function co ...
最新文章
- 文件编程之Linux下系统调用
- 机器学习漫谈:深度学习的辉煌
- android api 中文 (73)—— AdapterView
- 沃顿商学院:价格杠杆,企业竞争的底层逻辑
- HOW-TO:带有Spring MVC的Tomcat中的自定义错误页面
- java获取cpu核数_vn.py社区精选12 - 策略参数优化,你需要懂得压榨CPU!
- Play framework logging设置
- 开辟 Dart 到 Native 的超级通道,饿了么跨平台的最佳实践
- [Android Pro] 判断Uri对应的ContentProvider所操作的数据库u存在,及DownloadManager的暂停,继续...
- Bailian2980 大整数乘法【大数】
- Java项目-食堂菜品点评系统(SpringBoot + SpringSecurity + Thymeleaf + Redis)
- 视频基础 以及 MP4 容器解封装
- 权限漏洞:水平权限漏洞、垂直权限漏洞
- 含泪整理最优质时间轴网页特效素材,你想要的这里都有
- ARCHPR(暴力破解压缩包密码软件)
- 古体字与简体字对照表_常用繁体字与简体字对照表
- SPSS免费安装教程(详细版)
- LTspice - 基本操作
- (完结项目)fpga采集双路CCD摄像头1000帧图像上传到上位机显示
- Launcher3之应用卸载过程分析
热门文章
- ubuntu安装python百度经验_如何在Ubuntu 20.04上安装Python 3.9(含python编译安装和使用Apt命令安装)...
- win7注册表无法修改计算机名称,Win7旗舰版
- php文章管理系统_PHP-小程序:(1)开发环境搭建
- 【转】Uncaught TypeError: Cannot set property ' ' of null 错误解决
- 改名之后的 Java EE,现在有什么新进展?
- Linux学习笔记第八周七次课(4月3日)
- python 的 virtualenv 环境搭建及 sublime 手动创建运行环境
- RH413--在RHEL6.4下测试nosuid和noexec选项
- php http 断点续传
- PHP函数调用及循环体内定义大型变量效率的研究