8月22日预习内容

流程控制

顺序结构
判断(分支选择)结构
循环结构

分支选择结构

if结构

int age = 20;
if (age > 18) {
String name = “Tom”;
System.out.println(“我叫” + name + “,已经” + age + “岁了,我成年了!”);
}

switch 结构

String color = “red”;
switch (color) {
case “red”: {
System.out.println(“红色”);
break;
}
case “blue”: {
System.out.println(“蓝色”);
break;
}
case “green”: {
System.out.println(“绿色”);
break;
}
default: {
System.out.println(“没有找到”);
break;
}
}

循环结构

while 结构

int sum = 0;
int i = 1;

while (i <= 10) {
sum = sum + i;
i++;
}

System.out.println(sum);

do-while 结构

int i = 1;
int sum = 0;

do {
sum += i++;
} while (i <= 10);

System.out.println(sum);

for 循环

int sum = 0;
for (int i = 1; i <= 28; i++) {
sum = sum + i;
}
System.out.println(sum);

控制循环结构

break:在循环体中,使用 break 关键字跳出整个循环。

int flag = 6;
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum = sum + i;
if (i == flag) {
break;
}
}
System.out.println(sum);
continue:在循环体中,使用 continue 跳出本次循环,循环还会继续执行。

int sum = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
sum = sum + i;
}
System.out.println(sum);

数组

存放的数据是相同的数据类型
数组的长度在定义时就确定了大小,数组是不可变长度的,或者说叫定长
数组中可以存放任意的数据类型(包含基本数据类型、引用数据类型、数组)
数组本身是引用数据类型(在栈内存中会存储其在堆内存中的引用地址)
type[] 变量名
静态初始化
int[] arrs2;
arrs2 = new int[]{1, 2 ,3 ,4};

int[] arrs = {1, 2, 3, 4};
动态初始化
type[] arrayName = new type[length];
foreach 遍历数组
for(int a : arrs3) {
System.out.println(a);
}

面向对象编程

面向过程和面向对象编程

类的定义
类的三大部件:成员变量、方法、构造器。
public class Student1 {
// 构造器
Student1(String name, int age, String code) {
this.name = name;
this.age = age;
this.code = code;
}

// 成员变量
String name;
int age;
String code;

// 方法
String intro() {
    return "我叫"+this.name+",我的学号是"+this.code+",我今年"+this.age+"岁了。";
}

void listen() {
    System.out.println(this.name + "在上课。");
}

}

隐藏和封装

Getter 和 Setter
package 和 import
访问控制修饰符

private:只能在当前类中被访问,一般用于对成员变量的修饰;
default:没有定义修饰符就是 default;
protected:可以在子类和本包中被访问,外部包不能被访问,在有一定业务意义的包中,可以定义类中成员变量是protected;
public:一般定义在方法或者一些常量中,用于外部接口的访问。

构造器重载

public Client1(int age, String code, String name) {
this(age);
this.name = name;
}

public Client1(String code) {
    this.code = code;
}

public Client1(int age) {
    // 复用
    if (age < 0 || age > 150) {
        System.out.println("不合法的年龄数据");
    } else {
        this.age = age;
    }   
}

猜你喜欢

转载自blog.csdn.net/moshangyi/article/details/81946510