需求:创建一个代表学生的类,并创建学生对象测试效果。属性只写出姓名、年龄即可,方法只写出学习、做作业即可。
学生类:
public class Student {
//属性
String name; //姓名
int age; //年龄
//方法
public void study() {
System.out.println(name + "正字努力学习Java面向对象");
}
public void doHomework() {
System.out.println(name + "正在努力做练习");
}
}
测试代码:
public static void main(String[] args) {
Student stu = new Student();
stu.name = "马化腾";
stu.age = 22;
stu.study();
stu.doHomework();
Student stu2 = new Student();
stu2.name = "李彦宏";
stu2.age = 19;
stu2.study();
stu2.doHomework();
}
需求:设计一个代表圆的类。要求能计算圆的周长和面积。
圆类代码:
public class Circle {
//属性
double r; //半径
//方法
//计算周长
public double primeter() {
return 2 * 3.1415926 * r;
}
//计算面积
public double area() {
return 3.1415926 * r * r;
}
}
测试代码:
public static void main(String[] args) {
Circle c1 = new Circle();
c1.r = 10;
System.out.println(c1.primeter());
System.out.println(c1.area());
Circle c2 = new Circle();
c2.r = 4;
System.out.println(c2.primeter());
System.out.println(c2.area());
}
需求:定义一个教师类,教师包含工号(num)和工资(salary)两个属性。定义一个数组,保存10名教师的信息。教师的编号从100开始,教师的工资是[8k, 15k]之间的一个数。打印出薪资是12k的教师的信息;对教师按薪资从小到大进行排序
教师类代码
public class Teacher {
int num; //工号
int salary; //工资
public void showInfo() {
System.out.println("工号:" + num + ",工资:" + salary);
}
}
测试代码
public static void main(String[] args) {
// 创建一个数组,保存10个教师
Teacher[] teachers = new Teacher[10];
// 创建Random对象,用于随机工资。
Random random = new Random();
// 通过循环创建10个教师,并放入数组中。
for (int i = 0; i < teachers.length; i++) {
Teacher t = new Teacher();
t.num = i + 100;
t.salary = (random.nextInt(15 - 8 + 1) + 8) * 1000;
teachers[i] = t;
}
// 遍历数组
for (int i = 0; i < teachers.length; i++) {
teachers[i].showInfo();
}
System.out.println("-----------");
// 查找工资为12k的教师
for (int i = 0; i < teachers.length; i++) {
if (teachers[i].salary == 12000) {
teachers[i].showInfo();
}
}
System.out.println("-----------");
// 按薪资从小到大对教师进行排序。冒泡法
for (int i = 0; i < teachers.length - 1; i++) {
for (int j = 0; j < teachers.length - 1 - i; j++) {
if (teachers[j].salary > teachers[j + 1].salary){
Teacher temp = teachers[j]; teachers[j] = teachers[j + 1];
teachers[j + 1] = temp;
}
}
}
// 遍历数组
for (int i = 0; i < teachers.length; i++) {
teachers[i].showInfo();
}
}