类和对象练习(秒懂)

需求:创建一个代表学生的类,并创建学生对象测试效果。属性只写出姓名、年龄即可,方法只写出学习、做作业即可。

学生类:

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(); 
	  		} 
	  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值