无参和有参创建对象
package day03;
public class Employee {
String ID;
String name;
double salary;
//无参构造
public Employee(){}
//有参构造
public Employee(String ID,String name,double salary){
this.ID = ID;
this.name = name;
this.salary = salary;
}
}
package day03;
public class EmployeeTest {
public static void main(String[] args) {
//利用无参创建对象
Employee emp1 = new Employee();
emp1.ID = "001";
emp1.name = "张三";
emp1.salary = 400.8;
Employee emp2 = new Employee();
emp2.ID = "002";
emp2.name = "李四";
emp2.salary = 500.89;
//利用有参创建对象
Employee emp3 = new Employee("003","赵五",600.55);
//创建一个数组手动放入
Employee[] arr1 = new Employee[2];
arr1[0] = emp1;
arr1[1] = emp2;
//创建一个数组,在创建时赋值
Employee[] arr2 = new Employee[] {emp1,emp2,emp3};
//找工资最高的对象
//找一个基准值对象
Employee temp = arr2[0];
for(int i = 0;i<arr2.length;i++) {
if(arr2[i].salary>temp.salary) {
temp = arr2[i];
}
}
System.out.println("工资最高者:"+temp.ID+","+temp.name+","+temp.salary);
}
}
总结:
- 在类模板中创建有参和无参两种方法。
- 数组可以在创建时赋值:Employee[] arr2 = new Employee[] {emp1,emp2,emp3};
- 在比较对象的值,并输出对象时,可以找一个基准对象。
练习
用户可以在终端上输入如下信息:
1,zhangsan,18,male,1383838338,北京
2,lisi,28,male,66668888,北京
3,wangwu,26,female,77888877,上海
要求你的程序能接收用户输入的这三行数据
并且将这些信息封装到3个对象中
然后求出这3个人的平均年龄,最大年龄
1、接收终端上的数据
2、定义一个类模板
3、将收到的数据拆分出来分别赋予对象中的属性变量
4、写一个算法,得到平均年龄,得到最大年龄
package day03;
public class Customer {
String ID;
String name;
int age;
String sex;
String tel;
String adrr;
public Customer(String iD, String name, int age, String sex, String tel, String adrr) {
ID = iD;
this.name = name;
this.age = age;
this.sex = sex;
this.tel = tel;
this.adrr = adrr;
}
}
package day03;
import java.util.Scanner;
public class CustomerTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("输入第一名顾客信息:");
String cus1 = input.nextLine();
String split1[] = cus1.split(",");
System.out.println("输入第二名顾客信息:");
String cus2 = input.nextLine();
String split2[] = cus2.split(",");
System.out.println("输入第三名顾客信息:");
String cus3 = input.nextLine();
String split3[] = cus3.split(",");
Customer customer1 = new Customer(split1[0], split1[1], Integer.parseInt(split1[2]), split1[3], split1[4], split1[5]);
Customer customer2 = new Customer(split2[0], split2[1], Integer.parseInt(split2[2]), split2[3], split2[4], split2[5]);
Customer customer3 = new Customer(split3[0], split3[1], Integer.parseInt(split3[2]), split3[3], split3[4], split3[5]);
//求平均年龄
double sum = customer1.age + customer2.age + customer3.age;
double AVE = sum/3;
System.out.println("平均年龄:"+AVE);
//三个对象放到数组中
Customer[] customers = new Customer[] {customer1,customer2,customer3};
//求最大年龄
Customer temp = customers[0];
for(int i = 0;i<customers.length;i++) {
if(customers[i].age>temp.age) {
temp = customers[i];
}
}
System.out.println("年龄最大者:"+temp.name+","+temp.age);
}
}
总结:
- 字符串切割 :String split2[] = cus2.split(",");