Java基础语法03-顺序结构、循环结构、方法的使用与重载、数组

1. 流程控制语句

1.1 顺序结构

public class Demo01Sequence {
	public static void main(String[] args) {
		System.out.println("今天天气不错");
		System.out.println("挺风和日丽的");
		System.out.println("我们下午没课");
		System.out.println("这的确挺爽的");
	}
}

1.2 选择结构

1.2.1 单if语句

public class Demo02If {
	public static void main(String[] args) {
		System.out.println("今天天气不错,正在压马路……突然发现一个快乐的地方:网吧");
		int age = 19;
		if (age >= 18) {
			System.out.println("进入网吧,开始high!");
			System.out.println("遇到了一群猪队友,开始骂街。");
			System.out.println("感觉不爽,结账走人。");
		}
		System.out.println("回家吃饭");
	}
}

1.2.2 标准的if-else语句

public class Demo03IfElse {
	public static void main(String[] args) {
		int num = 666;
		if (num % 2 == 0) { // 如果除以2能够余数为0,说明是偶数
			System.out.println("偶数");
		} else {
			System.out.println("奇数");
		}
	}
}

1.2.3 拓展的if-else语句

// x和y的关系满足如下:
// 如果x >= 3,那么y = 2x + 1;
// 如果-1 < x < 3,那么y = 2x;
// 如果x <= -1,那么y = 2x – 1;
public class Demo04IfElseExt {
	public static void main(String[] args) {
		int x = -10;
		int y;
		if (x >= 3) {
			y = 2 * x + 1;
		} else if (-1 < x && x < 3) {
			y = 2 * x;
		} else {
			y = 2 * x - 1;
		}
		System.out.println("结果是:" + y);
	}
}
1.2.3.1 用if语句实现考试成绩
public class Demo05IfElsePractise {
	public static void main(String[] args) {
		int score = 120;
		if (score >= 90 && score <= 100) {
			System.out.println("优秀");
		} else if (score >= 80 && score < 90) {
			System.out.println("好");
		} else if (score >= 70 && score < 80) {
			System.out.println("良");
		} else if (score >= 60 && score < 70) {
			System.out.println("及格");
		} else if (score >= 0 && score < 60) {
			System.out.println("不及格");
		} else { // 单独处理边界之外的不合理情况
			System.out.println("数据错误");
		}
	}
}
1.2.3.2 用if语句替换三元运算符
// 题目:使用三元运算符和标准的if-else语句分别实现:取两个数字当中的最大值
public class Demo06Max {
	public static void main(String[] args) {
		int a = 105;
		int b = 20;
		// 首先使用三元运算符
		// int max = a > b ? a : b;
		// 使用今天的if语句
		int max;
		if (a > b) {
			max = a;
		} else {
			max = b;
		}
		System.out.println("最大值:" + max);
	}
}

1.2.4 标准的switch语句

public class Demo07Switch {
	public static void main(String[] args) {
		int num = 10;
		
		switch (num) {
			case 1:
				System.out.println("星期一");
				break;
			case 2:
				System.out.println("星期二");
				break;
			case 3:
				System.out.println("星期三");
				break;
			case 4:
				System.out.println("星期四");
				break;
			case 5:
				System.out.println("星期五");
				break;
			case 6:
				System.out.println("星期六");
				break;
			case 7:
				System.out.println("星期日");
				break;
			default:
				System.out.println("数据不合理");
				break; // 最后一个break语句可以省略,但是强烈推荐不要省略
		}
	}
}

1.2.5 穿透的switch语句

/*
switch语句使用的注意事项:
1. 多个case后面的数值不可以重复。
2. switch后面小括号当中只能是下列数据类型:
基本数据类型:byte/short/char/int
引用数据类型:String字符串、enum枚举
3. switch语句格式可以很灵活:前后顺序可以颠倒,而且break语句还可以省略。
“匹配哪一个case就从哪一个位置向下执行,直到遇到了break或者整体结束为止。”使用break避免穿透。
*/
public class Demo08SwitchNotice {
	public static void main(String[] args) {
		int num = 2;
		switch (num) {
			case 1:
				System.out.println("你好");
				break;
			case 2:
				System.out.println("我好");
				// break;
			case 3:
				System.out.println("大家好");
				break;
			default:
				System.out.println("他好,我也好。");
				break;
		} // switch
	}
}

1.3 循环结构

循环结构的基本组成部分,一般可以分成四部分:

  1. 初始化语句:在循环开始最初执行,而且只做唯一一次。
  2. 条件判断:如果成立,则循环继续;如果不成立,则循环退出。
  3. 循环体:重复要做的事情内容,若干行语句。
  4. 步进语句:每次循环之后都要进行的扫尾工作,每次循环结束之后都要执行一次。

1.3.1 for循环

public class Demo09For {
	public static void main(String[] args) {
		for (int i = 1; i <= 100; i++) {
			System.out.println("我错啦!原谅我吧!" + i);
		}
		System.out.println("程序停止");
	}
}

1.3.2 while循环

while循环有一个标准格式,还有一个扩展格式。

标准格式:
while (条件判断) {
循环体
}

扩展格式:
初始化语句;
while (条件判断) {
循环体;
步进语句;
}

public class Demo10While {
	public static void main(String[] args) {
		for (int i = 1; i <= 10; i++) {
			System.out.println("我错啦!" + i);
		}
		System.out.println("=================");
		
		int i = 1; // 1. 初始化语句
		while (i <= 10) { // 2. 条件判断
			System.out.println("我错啦!" + i); // 3. 循环体
			i++; // 4. 步进语句
		}
	}
}

1.3.3 do while循环

do-while循环的标准格式:

do {
循环体
} while (条件判断);

扩展格式:
初始化语句
do {
循环体
步进语句
} while (条件判断);

public class Demo11DoWhile {
	public static void main(String[] args) {
		for (int i = 1; i <= 10; i++) {
			System.out.println("原谅你啦!起来吧!地上怪凉!" + i);
		}
		System.out.println("===============");
		
		int i = 1; // 1. 初始化语句
		do {
			System.out.println("原谅你啦!起来吧!地上怪凉!" + i); // 3. 循环体
			i++; // 4. 步进语句
		} while (i <= 10); // 2. 条件判断
	}
}

1.3.4 题目:求出1-100之间的偶数和。

思路:

  1. 既然范围已经确定了是1到100之间,那么我就从1、2、3……一直到100这么多数字一个一个进行检查。
  2. 总共有100个数字,并非所有数字都能用。必须要是偶数才能用,判断(if语句)偶数:num % 2 == 0
  3. 需要一个变量,用来进行累加操作。也就好比是一个存钱罐。
public class Demo12HundredSum {
	public static void main(String[] args) {
		int sum = 0; // 用来累加的存钱罐
		
		for (int i = 1; i <= 100; i++) {
			if (i % 2 == 0) { // 如果是偶数
				sum += i;
			}
		}
		System.out.println("结果是:" + sum);
	}
}

1.3.5 三种循环的区别

三种循环的区别。

  1. 如果条件判断从来没有满足过,那么for循环和while循环将会执行0次,但是do-while循环会执行至少一次。
  2. for循环的变量在小括号当中定义,只有循环内部才可以使用。while循环和do-while循环初始化语句本来就在外面,所以出来循环之后还可以继续使用。
public class Demo13LoopDifference {
	public static void main(String[] args) {
		for (int i = 1; i < 0; i++) {
			System.out.println("Hello");
		}
		// System.out.println(i); // 这一行是错误写法!因为变量i定义在for循环小括号内,只有for循环自己才能用。
		System.out.println("================");
		
		int i = 1;
		do {
			System.out.println("World");
			i++;
		} while (i < 0);
		// 现在已经超出了do-while循环的范围,我们仍然可以使用变量i
		System.out.println(i); // 2
	}
}

1.3.6 break语句

break关键字的用法有常见的两种:

  1. 可以用在switch语句当中,一旦执行,整个switch语句立刻结束。
  2. 还可以用在循环语句当中,一旦执行,整个循环语句立刻结束。打断循环。

关于循环的选择,有一个小建议:
凡是次数确定的场景多用for循环;否则多用while循环。

public class Demo14Break {
	public static void main(String[] args) {
		for (int i = 1; i <= 10; i++) {
			// 如果希望从第4次开始,后续全都不要了,就要打断循环
			if (i == 4) { // 如果当前是第4次
				break; // 那么就打断整个循环
			}
			System.out.println("Hello" + i);
		}
	}
}

1.3.7 continue语句

另一种循环控制语句是continue关键字。
一旦执行,立刻跳过当前次循环剩余内容,马上开始下一次循环。

public class Demo15Continue {
	public static void main(String[] args) {
		for (int i = 1; i <= 10; i++) {
			if (i == 4) { // 如果当前是第4层
				continue; // 那么跳过当前次循环,马上开始下一次(第5层)
			}
			System.out.println(i + "层到了。");
		}
	}
}

1.3.8 死循环

永远停不下来的循环,叫做死循环。
ctrl + c :强制停止死循环
死循环的标准格式:
while (true) {
循环体
}

public class Demo16DeadLoop {
	public static void main(String[] args) {
		while (true) {
			System.out.println("I Love Java!");
		}
		
		// System.out.println("Hello");
	}
}

1.3.9 循环嵌套(输出一天的时间)

利用循环嵌套输出时间,分钟,秒

public class Demo17LoopHourAndMinute {
	public static void main(String[] args) {
		for (int hour = 0; hour < 24; hour++) { // 外层控制小时
			for (int minute = 0; minute < 60; minute++) { // 内层控制小时之内的分钟
				for (int second = 0; second < 60; second++){
					System.out.println(hour + "点" + minute + "分" + second + "秒");
				}
				
			}

		}
	}
}

2. IDEA快捷键

快捷键功能
Alt+Enter导入包,自动修正代码
Ctrl+Y删除光标所在行
Ctrl+D复制光标所在行的内容,插入光标位置下面
Ctrl+Alt+L格式化代码
Ctrl+/单行注释
Ctrl+Shift+/选中代码注释,多行注释,再按取消注释
Alt+Ins自动生成代码,toString,get,set等方法
Alt+Shift+上下箭头移动当前代码行
Shift+F6改变所有同名的变量名

3. 方法复习

3.1 简单方法的使用

复习一下此前学习的方法基础入门知识。

定义格式:
public static void 方法名称() {
方法体
}

调用格式:
方法名称();

注意事项:

  1. 方法定义的先后顺序无所谓。
  2. 方法定义必须是挨着的,不能在一个方法的内部定义另外一个方法。
  3. 方法定义之后,自己不会执行的;如果希望执行,一定要进行方法的调用。
public class Demo01Method {

    public static void main(String[] args) {
        printMethod();
    }
    public static void printMethod() {
        for (int j = 0; j < 5; j++) {
            for (int i = 0; i < 20; i++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

3.2 方法的定义及三种调用格式

方法其实就是若干语句的功能集合。

方法好比是一个工厂。
蒙牛工厂 原料:奶牛、饲料、水
产出物:奶制品
钢铁工厂 原料:铁矿石、煤炭
产出物:钢铁建材

参数(原料):就是进入方法的数据。
返回值(产出物):就是从方法中出来的数据。

定义方法的完整格式:
修饰符 返回值类型 方法名称(参数类型 参数名称, …) {
  方法体
   return 返回值;
}

修饰符:现阶段的固定写法,public static
返回值类型:也就是方法最终产生的数据结果是什么类型
方法名称:方法的名字,规则和变量一样,小驼峰
参数类型:进入方法的数据是什么类型
参数名称:进入方法的数据对应的变量名称
PS:参数如果有多个,使用逗号进行分隔
方法体:方法需要做的事情,若干行代码
return:两个作用,第一停止当前方法,第二将后面的返回值还给调用处
返回值:也就是方法执行后最终产生的数据结果

注意:return后面的“返回值”,必须和方法名称前面的“返回值类型”,保持对应。

定义一个两个int数字相加的方法。三要素:
返回值类型:int
方法名称:sum
参数列表:int a, int b

方法的三种调用格式。

  1. 单独调用:方法名称(参数);
  2. 打印调用:System.out.println(方法名称(参数));
  3. 赋值调用:数据类型 变量名称 = 方法名称(参数);

注意:此前学习的方法,返回值类型固定写为void,这种方法只能够单独调用,不能进行打印调用或者赋值调用。

public class Demo02MethodDefine {
    public static void main(String[] args) {
        // 单独调用
        sum(10, 20);
        System.out.println("===========");

        // 打印调用
        System.out.println(sum(10, 20)); // 30
        System.out.println("===========");

        // 赋值调用
        int number = sum(15, 25);
        number += 100;
        System.out.println("变量的值:" + number); // 140
    }

    public static int sum(int a, int b) {
        System.out.println("方法执行啦!");
        int result = a + b;
        return result;
    }
}

3.3 有参数和无参数对比

有参数:小括号当中有内容,当一个方法需要一些数据条件,才能完成任务的时候,就是有参数。
例如两个数字相加,必须知道两个数字是各自多少,才能相加。

无参数:小括号当中留空。一个方法不需要任何数据条件,自己就能独立完成任务,就是无参数。
例如定义一个方法,打印固定10次HelloWorld。

public class Demo03MethodParam {

    public static void main(String[] args) {
        method1(10, 20);
        System.out.println("==============");
        method2();
    }

    // 两个数字相乘,做乘法,必须知道两个数字各自是多少,否则无法进行计算
    // 有参数
    public static void method1(int a, int b) {
        int result = a * b;
        System.out.println("结果是:" + result);
    }

    // 例如打印输出固定10次文本字符串
    public static void method2() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Hello, World!" + i);
        }
    }

}

3.4 有返回值和无返回值对比

题目要求:定义一个方法,用来【求出】两个数字之和。(你帮我算,算完之后把结果告诉我。)
题目变形:定义一个方法,用来【打印】两个数字之和。(你来计算,算完之后你自己负责显示结果,不用告诉我。)

注意事项:
对于有返回值的方法,可以使用单独调用、打印调用或者赋值调用。
但是对于无返回值的方法,只能使用单独调用,不能使用打印调用或者赋值调用。

public class Demo04MethodReturn {

    public static void main(String[] args) {
        // 我是main方法,我来调用你。
        // 我调用你,你来帮我计算一下,算完了之后,把结果告诉我的num变量
        int num = getSum(10, 20);
        System.out.println("返回值是:" + num);
        System.out.println("==============");

        printSum(100, 200);
        System.out.println("==============");

        System.out.println(getSum(2, 3)); // 正确写法
        getSum(3, 5); // 正确写法,但是返回值没有用到
        System.out.println("==============");

        // 对于void没有返回值的方法,只能单独调用,不能打印或者赋值
//        System.out.println(printSum(2, 3)); // 错误写法!
//        System.out.println(void);

//        int num2 = printSum(10, 20); // 错误写法!
//        int num3 = void;
//        void num4 = void;
    }

    // 我是一个方法,我负责两个数字相加。
    // 我有返回值int,谁调用我,我就把计算结果告诉谁
    public static int getSum(int a, int b) {
        int result = a + b;
        return result;
    }

    // 我是一个方法,我负责两个数字相加。
    // 我没有返回值,不会把结果告诉任何人,而是我自己进行打印输出。
    public static void printSum(int a, int b) {
        int result = a + b;
        System.out.println("结果是:" + result);
    }

}

3.5 题目:比较两个数字大小

题目要求:
定义一个方法,用来判断两个数字是否相同。

public class Demo01MethodSame {

    public static void main(String[] args) {
        System.out.println(isSame(10, 20)); // false
        System.out.println(isSame(20, 20)); // true
    }

    /*
    三要素:
    返回值类型:boolean
    方法名称:isSame
    参数列表:int a, int b
     */
    public static boolean isSame(int a, int b) {
        /*boolean same;
        if (a == b) {
            same = true;
        } else {
            same = false;
        }*/

        // boolean same = a == b ? true : false;

        // boolean same = a == b;

        return a == b;
    }

}

3.6 题目:求出1到100的和

题目要求:
定义一个方法,用来求出1-100之间所有数字的和值。

public class Demo02MethodSum {

    public static void main(String[] args) {
        System.out.println("结果是:" + getSum());
    }

    /*
    三要素
    返回值:有返回值,计算结果是一个int数字
    方法名称:getSum
    参数列表:数据范围已经确定,是固定的,所以不需要告诉我任何条件,不需要参数
     */
    public static int getSum() {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        return sum;
    }

}

3.7 题目:打印指定次数

题目要求:
定义一个方法,用来打印指定次数的HelloWorld。

public class Demo03MethodPrint {

    public static void main(String[] args) {
        printCount(10);
    }

    /*
    三要素
    返回值类型:只是进行一大堆打印操作而已,没有计算,也没有结果要告诉调用处
    方法名称:printCount
    参数列表:到底要打印多少次?必须告诉我,否则我不知道多少次,没法打印。次数:int
     */
    public static void printCount(int num) {
        for (int i = 0; i < num; i++) {
            System.out.println("Hello, World!" + (i + 1));
        }
    }

}

3.8 方法的注意事项

使用方法的时候,注意事项:

  1. 方法应该定义在类当中,但是不能在方法当中再定义方法。不能嵌套。
  2. 方法定义的前后顺序无所谓。
  3. 方法定义之后不会执行,如果希望执行,一定要调用:单独调用、打印调用、赋值调用。
  4. 如果方法有返回值,那么必须写上“return 返回值;”,不能没有。
  5. return后面的返回值数据,必须和方法的返回值类型,对应起来。
  6. 对于一个void没有返回值的方法,不能写return后面的返回值,只能写return自己。
  7. 对于void方法当中最后一行的return可以省略不写。
  8. 一个方法当中可以有多个return语句,但是必须保证同时只有一个会被执行到,两个return不能连写。
public class Demo04MethodNotice {

    public static int method1() {
        return 10;
    }

    public static void method2() {
//        return 10; // 错误的写法!方法没有返回值,return后面就不能写返回值。
        return; // 没有返回值,只是结束方法的执行而已。
    }

    public static void method3() {
        System.out.println("AAA");
        System.out.println("BBB");
//        return; // 最后一行的return可以省略不写。
    }

    public static int getMax(int a, int b) {
        /*int max;
        if (a > b) {
            max = a;
        } else {
            max = b;
        }
        return max;*/

        if (a > b) {
            return a;
        } else {
            return b;
        }
    }

}

4. 方法重载

4.1 基本使用及注意事项

对于功能类似的方法来说,因为参数列表不一样,却需要记住那么多不同的方法名称,太麻烦。

方法的重载(Overload):多个方法的名称一样,但是参数列表不一样。
好处:只需要记住唯一一个方法名称,就可以实现类似的多个功能。

方法重载与下列因素相关:

  1. 参数个数不同
  2. 参数类型不同
  3. 参数的多类型顺序不同

方法重载与下列因素无关:

  1. 与参数的名称无关
  2. 与方法的返回值类型无关
public class Demo01MethodOverload {

    public static void main(String[] args) {
        /*System.out.println(sumTwo(10, 20)); // 30
        System.out.println(sumThree(10, 20, 30)); // 60
        System.out.println(sumFour(10, 20, 30, 40)); // 100*/

        System.out.println(sum(10, 20)); // 两个参数的方法
        System.out.println(sum(10, 20, 30)); // 三个参数的方法
        System.out.println(sum(10, 20, 30, 40)); // 四个参数的方法
//        System.out.println(sum(10, 20, 30, 40, 50)); // 找不到任何方法来匹配,所以错误!

        sum(10, 20);
    }

    public static int sum(int a, double b) {
        return (int) (a + b);
    }

    public static int sum(double a, int b) {
        return (int) (a + b);
    }

    public static int sum(int a, int b) {
        System.out.println("有2个参数的方法执行!");
        return a + b;
    }

    // 错误写法!与方法的返回值类型无关
//    public static double sum(int a, int b) {
//        return a + b + 0.0;
//    }

    // 错误写法!与参数的名称无关
//    public static int sum(int x, int y) {
//        return x + y;
//    }

    public static int sum(double a, double b) {
        return (int) (a + b);
    }

    public static int sum(int a, int b, int c) {
        System.out.println("有3个参数的方法执行!");
        return a + b + c;
    }

    public static int sum(int a, int b, int c, int d) {
        System.out.println("有4个参数的方法执行!");
        return a + b + c + d;
    }

}

4.2 题目:比较两个数据是否相等

题目要求:
比较两个数据是否相等。
参数类型分别为两个byte类型,两个short类型,两个int类型,两个long类型,并在main方法中进行测试。

public class Demo02MethodOverloadSame {

    public static void main(String[] args) {
        byte a = 10;
        byte b = 20;
        System.out.println(isSame(a, b));

        System.out.println(isSame((short) 20, (short) 20));

        System.out.println(isSame(11, 12));

        System.out.println(isSame(10L, 10L));
    }

    public static boolean isSame(byte a, byte b) {
        System.out.println("两个byte参数的方法执行!");
        boolean same;
        if (a == b) {
            same = true;
        } else {
            same = false;
        }
        return same;
    }

    public static boolean isSame(short a, short b) {
        System.out.println("两个short参数的方法执行!");
        boolean same = a == b ? true : false;
        return same;
    }

    public static boolean isSame(int a, int b) {
        System.out.println("两个int参数的方法执行!");
        return a == b;
    }

    public static boolean isSame(long a, long b) {
        System.out.println("两个long参数的方法执行!");
        if (a == b) {
            return true;
        } else {
            return false;
        }
    }

}

4.3 判断重载是否正确

public class Demo03OverloadJudge {

    /*
    public static void open(){} // 正确重载
    public static void open(int a){} // 正确重载
    static void open(int a,int b){} // 代码错误:和第8行冲突
    public static void open(double a,int b){} // 正确重载
    public static void open(int a,double b){} // 代码错误:和第6行冲突
    public void open(int i,double d){} // 代码错误:和第5行冲突
    public static void OPEN(){} // 代码正确不会报错,但是并不是有效重载
    public static void open(int i,int j){} // 代码错误:和第3行冲突
    */

}

4.4 实现重载的print

byte short int long float double char boolean
String
在调用输出语句的时候,println方法其实就是进行了多种数据类型的重载形式。

public class Demo04OverloadPrint {

    public static void main(String[] args) {
        myPrint(100); // int
        myPrint("Hello"); // String
    }

    public static void myPrint(byte num) {
        System.out.println(num);
    }

    public static void myPrint(short num) {
        System.out.println(num);
    }

    public static void myPrint(int num) {
        System.out.println(num);
    }

    public static void myPrint(long num) {
        System.out.println(num);
    }

    public static void myPrint(float num) {
        System.out.println(num);
    }

    public static void myPrint(double num) {
        System.out.println(num);
    }

    public static void myPrint(char zifu) {
        System.out.println(zifu);
    }

    public static void myPrint(boolean is) {
        System.out.println(is);
    }

    public static void myPrint(String str) {
        System.out.println(str);
    }

}

5. 数组

5.1 数组的概念

数组的概念:是一种容器,可以同时存放多个数据值。

数组的特点:

  1. 数组是一种引用数据类型
  2. 数组当中的多个数据,类型必须统一
  3. 数组的长度在程序运行期间不可改变

5.2 数组的动态初始化和静态初始化

数组的初始化:在内存当中创建一个数组,并且向其中赋予一些默认值。

两种常见的初始化方式:

  1. 动态初始化(指定长度)
  2. 静态初始化(指定内容)

动态初始化数组的格式:
数据类型[ ] 数组名称 = new 数据类型[数组长度];

解析含义:
左侧数据类型:也就是数组当中保存的数据,全都是统一的什么类型
左侧的中括号:代表我是一个数组
左侧数组名称:给数组取一个名字
右侧的new:代表创建数组的动作
右侧数据类型:必须和左边的数据类型保持一致
右侧中括号的长度:也就是数组当中,到底可以保存多少个数据,是一个int数字

public class Demo01Array {

    public static void main(String[] args) {
        // 创建一个数组,里面可以存放300个int数据
        // 格式:数据类型[] 数组名称 = new 数据类型[数组长度];
        int[] arrayA = new int[300];

        // 创建一个数组,能存放10个double类型的数据
        double[] arrayB = new double[10];

        // 创建一个数组,能存放5个字符串
        String[] arrayC = new String[5];
    }

}

动态初始化(指定长度):在创建数组的时候,直接指定数组当中的数据元素个数。
静态初始化(指定内容):在创建数组的时候,不直接指定数据个数多少,而是直接将具体的数据内容进行指定。

静态初始化基本格式:
数据类型[ ] 数组名称 = new 数据类型[ ] { 元素1, 元素2, … };

注意事项:
虽然静态初始化没有直接告诉长度,但是根据大括号里面的元素具体内容,也可以自动推算出来长度。

public class Demo02Array {

    public static void main(String[] args) {
        // 直接创建一个数组,里面装的全都是int数字,具体为:5、15、25
        int[] arrayA = new int[] { 5, 15, 25, 40 };

        // 创建一个数组,用来装字符串:"Hello"、"World"、"Java"
        String[] arrayB = new String[] { "Hello", "World", "Java" };
    }

}

使用静态初始化数组的时候,格式还可以省略一下。

标准格式:
数据类型[ ] 数组名称 = new 数据类型[] { 元素1, 元素2, … };

省略格式:
数据类型[ ] 数组名称 = { 元素1, 元素2, … };

注意事项:

  1. 静态初始化没有直接指定长度,但是仍然会自动推算得到长度。
  2. 静态初始化标准格式可以拆分成为两个步骤。
  3. 动态初始化也可以拆分成为两个步骤。
  4. 静态初始化一旦使用省略格式,就不能拆分成为两个步骤了。

使用建议:
如果不确定数组当中的具体内容,用动态初始化;否则,已经确定了具体的内容,用静态初始化。

public class Demo03Array {

    public static void main(String[] args) {
        // 省略格式的静态初始化
        int[] arrayA = { 10, 20, 30 };

        // 静态初始化的标准格式,可以拆分成为两个步骤
        int[] arrayB;
        arrayB = new int[] { 11, 21, 31 };

        // 动态初始化也可以拆分成为两个步骤
        int[] arrayC;
        arrayC = new int[5];

        // 静态初始化的省略格式,不能拆分成为两个步骤。
//        int[] arrayD;
//        arrayD = { 10, 20, 30 };
    }

}

5.3 访问数组元素进行获取

直接打印数组名称,得到的是数组对应的:内存地址哈希值。
二进制:01
十进制:0123456789
16进制:0123456789abcdef

访问数组元素的格式:数组名称[索引值]
索引值:就是一个int数字,代表数组当中元素的编号。
【注意】索引值从0开始,一直到“数组的长度-1”为止。

public class Demo04ArrayUse {

    public static void main(String[] args) {
        // 静态初始化的省略格式
        int[] array = { 10, 20, 30 };

        System.out.println(array); // [I@75412c2f

        // 直接打印数组当中的元素
        System.out.println(array[0]); // 10
        System.out.println(array[1]); // 20
        System.out.println(array[2]); // 30
        System.out.println("=============");

        // 也可以将数组当中的某一个单个元素,赋值交给变量
        int num = array[1];
        System.out.println(num); // 20
    }

}

5.4 访问数组元素进行赋值

使用动态初始化数组的时候,其中的元素将会自动拥有一个默认值。规则如下:
如果是整数类型,那么默认为0;
如果是浮点类型,那么默认为0.0;
如果是字符类型,那么默认为’\u0000’;
如果是布尔类型,那么默认为false;
如果是引用类型,那么默认为null。

注意事项:
静态初始化其实也有默认值的过程,只不过系统自动马上将默认值替换成为了大括号当中的具体数值。

public class Demo05ArrayUse {

    public static void main(String[] args) {
        // 动态初始化一个数组
        int[] array = new int[3];

        System.out.println(array); // 内存地址值
        System.out.println(array[0]); // 0
        System.out.println(array[1]); // 0
        System.out.println(array[2]); // 0
        System.out.println("=================");

        // 将数据123赋值交给数组array当中的1号元素
        array[1] = 123;
        System.out.println(array[0]); // 0
        System.out.println(array[1]); // 123
        System.out.println(array[2]); // 0
    }

}

5.5 Java中的内存划分

在这里插入图片描述

5.6 一个/两个数组的内存图

一个数组的内存图
在这里插入图片描述
两个数组的内存图
在这里插入图片描述

5.7 两个引用指向同一个数组

public class Demo03ArraySame {

    public static void main(String[] args) {
        int[] arrayA = new int[3];
        System.out.println(arrayA); // 地址值
        System.out.println(arrayA[0]); // 0
        System.out.println(arrayA[1]); // 0
        System.out.println(arrayA[2]); // 0
        System.out.println("==============");

        arrayA[1] = 10;
        arrayA[2] = 20;
        System.out.println(arrayA); // 地址值
        System.out.println(arrayA[0]); // 0
        System.out.println(arrayA[1]); // 10
        System.out.println(arrayA[2]); // 20
        System.out.println("==============");

        // 将arrayA数组的地址值,赋值给arrayB数组
        int[] arrayB = arrayA;
        System.out.println(arrayB); // 地址值
        System.out.println(arrayB[0]); // 0
        System.out.println(arrayB[1]); // 10
        System.out.println(arrayB[2]); // 20
        System.out.println("==============");

        arrayB[1] = 100;
        arrayB[2] = 200;
        System.out.println(arrayB); // 地址值
        System.out.println(arrayB[0]); // 0
        System.out.println(arrayB[1]); // 100
        System.out.println(arrayB[2]); // 200
    }

}

在这里插入图片描述

5.8 数组索引越界异常

数组的索引编号从0开始,一直到“数组的长度-1”为止。

如果访问数组元素的时候,索引编号并不存在,那么将会发生
数组索引越界异常
ArrayIndexOutOfBoundsException

原因:索引编号写错了。
解决:修改成为存在的正确索引编号。

 public class Demo01ArrayIndex {

            public static void main(String[] args) {
                int[] array = { 15, 25, 35 };

                System.out.println(array[0]); //15
        System.out.println(array[1]); // 25
        System.out.println(array[2]); // 35

        // 错误写法
        // 并不存在3号元素,所以发生异常
        System.out.println(array[3]);
    }

}

5.9 空指针异常

所有的引用类型变量,都可以赋值为一个null值。但是代表其中什么都没有。

数组必须进行new初始化才能使用其中的元素。
如果只是赋值了一个null,没有进行new创建,
那么将会发生:
空指针异常 NullPointerException

原因:忘了new
解决:补上new

public class Demo02ArrayNull {

    public static void main(String[] args) {
        int[] array = null;
//        array = new int[3];
        System.out.println(array[0]);
    }

}

5.10 获取数组的长度

如何获取数组的长度,格式:
数组名称.length

这将会得到一个int数字,代表数组的长度。

数组一旦创建,程序运行期间,长度不可改变。

public class Demo03ArrayLength {

    public static void main(String[] args) {
        int[] arrayA = new int[3];

        int[] arrayB = {10, 20, 30, 3, 5, 4, 6, 7, 8, 8, 65, 4};
        int len = arrayB.length;
        System.out.println("arrayB数组的长度是:" + len);
        System.out.println("=============");

        int[] arrayC = new int[3];
        System.out.println(arrayC.length); // 3
        arrayC = new int[5];
        System.out.println(arrayC.length); // 5
    }

}

5.11 数组的遍历输出

遍历数组,说的就是对数组当中的每一个元素进行逐一、挨个儿处理。默认的处理方式就是打印输出。

public class Demo04Array {

    public static void main(String[] args) {
        int[] array = { 15, 25, 30, 40, 50, 60, 75 };

        // 首先使用原始方式
        System.out.println(array[0]); // 15
        System.out.println(array[1]); // 25
        System.out.println(array[2]); // 30
        System.out.println(array[3]); // 40
        System.out.println(array[4]); // 50
        System.out.println(array[5]); // 50
        System.out.println("=================");

        // 使用循环,次数其实就是数组的长度。
        for (int i = 0; i < 6; i++) {
            System.out.println(array[i]);
        }
        System.out.println("=================");

//        int len = array.length; // 长度
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }

}

5.12 求出数组中的最值

public class Demo05ArrayMax {

    public static void main(String[] args) {
        int[] array = { 5, 15, 30, 20, 10000, 30, 35 };

        int max = array[0]; // 比武擂台
        for (int i = 1; i < array.length; i++) {
            // 如果当前元素,比max更大,则换人
            if (array[i] > max) {
                max = array[i];
            }
        }
        // 谁最后最厉害,就能在max当中留下谁的战斗力
        System.out.println("最大值:" + max);
    }

}
public class Demo06ArrayMin {

    public static void main(String[] args) {
        int[] array = { 5, 15, 30, 20, 10000, -20, 30, 35 };

        int min = array[0]; // 比武擂台
        for (int i = 1; i < array.length; i++) {
            // 如果当前元素,比min更小,则换人
            if (array[i] < min) {
                min = array[i];
            }
        }
        System.out.println("最小值:" + min);
    }

}

5.13 数组元素反转

数组元素的反转:
本来的样子:[1, 2, 3, 4]
之后的样子:[4, 3, 2, 1]

要求不能使用新数组,就用原来的唯一一个数组。
在这里插入图片描述

public class Demo07ArrayReverse {

    public static void main(String[] args) {
        int[] array = { 10, 20, 30, 40, 50 };

        // 遍历打印数组本来的样子
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
        System.out.println("============");

        /*
        初始化语句:int min = 0, max = array.length - 1
        条件判断:min < max
        步进表达式:min++, max--
        循环体:用第三个变量倒手
         */
        for (int min = 0, max = array.length - 1; min < max; min++, max--) {
            int temp = array[min];
            array[min] = array[max];
            array[max] = temp;
        }

        // 再次打印遍历输出数组后来的样子
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }

}

5.14 数组作为方法参数传递

数组可以作为方法的参数。
当调用方法的时候,向方法的小括号进行传参,传递进去的其实是数组的地址值。

public class Demo01ArrayParam {

    public static void main(String[] args) {
        int[] array = { 10, 20, 30, 40, 50 };

        System.out.println(array); // 地址值

        printArray(array); // 传递进去的就是array当中保存的地址值
        System.out.println("==========AAA==========");
        printArray(array);
        System.out.println("==========BBB==========");
        printArray(array);
    }

    /*
    三要素
    返回值类型:只是进行打印而已,不需要进行计算,也没有结果,用void
    方法名称:printArray
    参数列表:必须给我数组,我才能打印其中的元素。int[] array
     */
    public static void printArray(int[] array) {
        System.out.println("printArray方法收到的参数是:");
        System.out.println(array); // 地址值
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }

}

5.15 数组作为方法返回值返回

一个方法可以有0、1、多个参数;但是只能有0或者1个返回值,不能有多个返回值。
如果希望一个方法当中产生了多个结果数据进行返回,怎么办?
解决方案:使用一个数组作为返回值类型即可。

任何数据类型都能作为方法的参数类型,或者返回值类型。

数组作为方法的参数,传递进去的其实是数组的地址值。
数组作为方法的返回值,返回的其实也是数组的地址值。

public class Demo02ArrayReturn {

    public static void main(String[] args) {
        int[] result = calculate(10, 20, 30);

        System.out.println("main方法接收到的返回值数组是:");
        System.out.println(result); // 地址值

        System.out.println("总和:" + result[0]);
        System.out.println("平均数:" + result[1]);
    }

    public static int[] calculate(int a, int b, int c) {
        int sum = a + b + c; // 总和
        int avg = sum / 3; // 平均数
        // 两个结果都希望进行返回

        // 需要一个数组,也就是一个塑料兜,数组可以保存多个结果
        /*
        int[] array = new int[2];
        array[0] = sum; // 总和
        array[1] = avg; // 平均数
        */

        int[] array = { sum, avg };
        System.out.println("calculate方法内部数组是:");
        System.out.println(array); // 地址值
        return array;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值