内容回顾:
流程控制语句:
if语句的三种格式:
格式1:
if(表达式){
语句1;
}
格式2:
if(表达式){
语句一;
}else(表达式2){
语句二;
}
格式3:
if(){
}else if(){
else if(){
...
}else(){
}
switch语句:
switch(表达式){
case 值1
语句1;
break;
case 值2
语句2;
break;
...
default
语句n;
break;
}
循环语句:
for循环:
for( ; ; ){
循环控制体;
}
统计思想;
求和思想;
while循环:
初始化语句;
while( ){
循环体语句;
控制体语句;
}
for语句与while语句的区别;
-
-
do while循环:
for循环的嵌套
经典左三角形;
*
* *
* * *
* * * *
* * * * *
for(int x = 1; x<=5;x++){ //控制行数
for(int = y;y<=5;y++){ //控制列数
System.out.print("*");
}
System.out.println();
}
经典三角形拓展练习: *九九乘法表*
for 循环整体不变,改变的是输出的文字;
for(int i = 1;i<=9;i++){
for(int j = 1;j<=9;j++){
System.out.print(i+"+"+j+"="+i*j+" ");
}
System.out.println();
}
跳转控制语句
break;跳出当前语句(switch/循环语句);
continue;跳出当前循环,继续下一次循环;
return;跳出当前方法;
方法
方法的格式
修饰符 返回值类型 方法名{参数类型1 参数名1,参数类型2 参数名2...... ){
代码块;
return 结果;
}
class FuntionDemo{
//定义方法add
public static int add(int x,int y){
return x+y ;
}
//主方法
public static void main(string [] args){
int a = 7;
int b = 5;
//调用方add
int z = add();
System.out.println(z);
}
}
练习题:
用键盘录入两个数据,返回较大值再比较两个数是否相等
class FuntionDemo{
//导包
import java.util.Scanner;
//定义方法add
public static int add(int x,int y){
return x+y ;
}
//定义方法bijiao
public static boolean bijiao(int x,int y){
return x==y;
}
//主方法
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个数: ");
//接收数据1
int a = sc.nextInt();
//接收数据2
System.out.println("请输入第二个数: ");
int a = sc.nextInt();
//调用方add
int z = add(a,b);
System.out.println(z);
/调用方法bijiao
boolean m =bijiao(a,b);
if(m){
System.out.println("它们相等");
}else{
System.out.println("它们不相等");
}
}
}
练习题:
方法的重载
方法的特点
- 返回值类型无关,只看方法名和参数列表
- 在调用时,虚拟机通过参数类表来区分同名方法
举例
public static void open(){}
public static void open(int a){}
public static void open(int a,int b){}
public static void open(double a,int b){}
public static void open(int a,double b){}
public void open(int i,double d){}
public static void open(int i,int j){}
不死兔子问题(**需使用递归**)
有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问第二十个月的兔子对数
数组
- 数组:可以存储多个元素的容器;(这多个元素必须是同一类型)
- 格式
数据类型 [ ] 数组名称;
数据类型 数组名称 [ ]; - 数组的初始化:
具体数组中的元素头系统默认给定,数组长度由开发者给定;
数据类型 数组名称 [ ] = new 数据类型[数组长度];
举例:int [] shuzu = new int [5];
定义了一个int类型的数组,这个数组中可以存放5个int类型的值
静态初始化
int[] arr = new int[] {88,45,23};
定义了一个int类型数组,这个数组中可以存放三个int类型的值,并且值分别是88,45,23.
可简化为: int[] arr = {88,45,23}
数组长度(属性)的获取:
数组名.length ;
举例 arr.length;
//数组的遍历
public static void main(String[] args){
int[] test = {43,81,3,53,21};
for(int i = 0;i<test.length;i++){
System.out.print(test[i]);
}
}
//数组获取最值
public static void main(String[] args){
//数组的初始化
int[] test1 = {12,23,34,7,45,56,67,95,6,85,74,63,52,43,32,21,3};
int max = test1[0];
//遍历的循环
for(int i = 1;i<(test1.length-1);i++) {
//判断
if(max<test1[i+1]) {
max = test1[i+1];
}
}
System.out.println(max);
}