PPT链接:点击这里
6、面向对象特征之三:多态性
-
理解多态性:可以理解为一个事物的多种态性
-
何为多态性
对象的多态性:父类的引用指向子类的对象(或子类的对象赋值给父类的引用)
-
多态的使用:虚拟方法调用
有了对象多态性以后,我们在编译期只能调用父类声明的方法,但在执行期实际执行的是子类重写父类的方法。简称:编译时看左边;运行时看右边
-
多态性的使用前提:①类的继承关系;②方法的重写
注意:对象的多态性只适用于方法,不适用于属性(编译和运行都看左边)
public class Person {
String name;
int age;
public void eat(){
System.out.println("人,吃饭");
}
public void walk(){
System.out.println("人,走路");
}
}
public class Woman extends Person{
boolean isBeauty;
public void goShopping(){
System.out.println("女人喜欢购物");
}
public void eat(){
System.out.println("女人少吃,为了减肥。");
}
public void walk(){
System.out.println("女人,窈窕的走路。");
}
}
public class Man extends Person{
boolean isSmoking;
public void earnMoney(){
System.out.println("男人负责工作养家");
}
public void eat() {
System.out.println("男人多吃肉,长肌肉");
}
public void walk() {
System.out.println("男人霸气的走路");
}
}
public class PersonTest {
public static void main(String[] args) {
//对象的多态性,父类的引用指向子类的对象
Person p2 = new Man();//(左:父类引用,右:子类对象)
Person p3 = new Woman();
//多态的使用:当调用子父类同名同参数方法时,实际调用的是子类重写父类的方法---虚拟方法调用
p2.eat();
p2.walk();
// p2.earnMoney();//错误:Person中没有定义earnMoney(),p2是Person的对象,编译时要从父类中找earnMoney(),运行时要从子类中找earnMoney()
}
}
![image-20221130102322353](https://i-blog.csdnimg.cn/blog_migrate/4dd6258bd90455ebb7c52a85dbddb46b.png)
多态性的应用举例
public class AnimalTest {
public static void main(String[] args) {
AnimalTest test = new AnimalTest();
test.func(new Dog());//输出狗
test.func(new Cat());//输出猫
}
//利用多态性:
public void func(Animal animal){//Animal animal = new Dog();
animal.eat();
animal.shout();
}
//如果没有多态性,就会写很多如下的方法,去调用
public void func(Dog dog){
dog.eat();
dog.shout();
}
public void func(Cat cat){
cat.eat();
cat.shout();
}
}
class Animal{
public void eat(){
System.out.println("动物,进食");
}
public void shout(){
System.out.println("动物:叫");
}
}
class Dog extends Animal{
public void eat(){
System.out.println("狗吃骨头");
}
public void shout() {
System.out.println("汪!汪!汪!");
}
}
class Cat extends Animal{
public void eat(){
System.out.println("猫吃鱼");
}
public void shout() {
System.out.println("喵!喵!喵!");
}
}
6.1、虚拟方法调用(Virtual Method Invocation)
虚拟方法调用举例
小结:方法的重载与重写
![]()
6.2、关键字:instanceof
-
a instanceof A
:判断 对象a 是否是 类A 的实例。如果是则返回true,如果不是则返回false -
使用情境:为了避免在向下转型时出现 ClassCastException 异常;我们在进行向下转型之前先进行 instanceof 的判断,如果返回true就进行向下转型,如果返回false,不进行向下转型
-
若 a instanceof A 返回true,则 a instanceof B 也返回true(B类是A类的父类)
public class PersonTest {
public static void main(String[] args) {
// 对象的多态性,父类的引用指向子类的对象
Person p2 = new Man();
p2.earnMoney();//错误
//不能调用子类所特有的方法、属性,编译时,p2是Person类型,
p2.name = "Tom";//正确,给父类中的name赋值
p2.isSmoking = true;//错误,isSmoking是子类中特有的属性
//【注意】有了对象的多态性以后,内存中实际上是加载了子类特有的属性和方法,但是由于变量声明为父类类型,导致编译时,只能调用父类中声明的属性和方法。子类的属性和方法不能调用
// 如何才能调用子类所特有的属性和方法?
// 使用强制类型转换符,也可称为:向下转型
Man m1 = (Man) p2;
m1.earnMoney();//正确
m1.isSmoking = true;
// 使用强转时,可能出现ClassCastException异常
// Woman w1 = (Woman)p2;//错误,p2是男人
// w1.goShopping();
//**************使用instanceof关键字***************
if (p2 instanceof Woman) {//如果p2是女人
Woman w1 = (Woman) p2;
w1.goShopping();
System.out.println("**********Woman*********");
}
if (p2 instanceof Man) {
Man m2 = (Man) p2;
m2.earnMoney();
System.out.println("*********Man************");
}
if (p2 instanceof Person) {
System.out.println("***********Person************");
}
if (p2 instanceof Object) {
System.out.println("***********object************");
}
//向下转型的常见问题
//问题1:编译时通过,运行时不通过
//举例一
Person p3 = new Woman();//Woman和Man没有任何关系
Man m3 = (Man)p3;
//举例二
Person p4 = new Person();
Man m4 = (Man)p4;
//问题二:编译通过,运行时也通过
Object obj = new Woman();//正确:Woman继承了Person, Person继承了Object; 既然obj能强转成Woman类型,obj就能转换成Person类型
Person p = (Person)obj;
//问题三:编译不通过
// Man m5 = new woman();//Woman和Man没有任何关系
// String str = new Date();//不相关的两个类不能赋值
// Object o = new Date();
// String str1 = (String)o;//错误
}
}
向上转型与向下转型
6.3、练习
6.3.1、练习1(面试题)
多态是编译时行为还是运行时行为
答:是运行时行为,因为运行时到底执行的是哪个子类的方法并不确定
【代码实现】
//证明如下:
import java.util.Random;
class Animal {
protected void eat() {
System.out.println("animal eat food");
}
}
class Cat extends Animal {
protected void eat() {
System.out.println("cat eat fish");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("Dog eat bone");
}
}
class Sheep extends Animal {
public void eat() {
System.out.println("Sheep eat grass");
}
}
public class InterviewTest {
public static Animal getInstance(int key) {
switch (key) {
case 0:
return new Cat ();
case 1:
return new Dog ();
default:
return new Sheep ();
}
}
public static void main(String[] args) {
int key = new Random().nextInt(3);
System.out.println(key);
Animal animal = getInstance(key);
animal.eat();
}
}
6.3.2、练习2(面试题)
知识点:
- 若子类重写了父类方法,就意味着子类里定义的方法彻底覆盖了父类里的同名方法,系统将不可能把父类里的方法转移到子类中:编译看左边,运行看右边
- 对于实例变量则不存在这样的现象,即使子类里定义了与父类完全相同的实例变量,这个实例变量依然不可能覆盖父类中定义的实例变量:编译运行都看左边
写出输出语句结果
class Base {
int count = 10;
public void display() {
System.out.println(this.count);
}
}
class Sub extends Base {
int count = 20;
public void display() {
System.out.println(this.count);
}
}
public class FieldMethodTest {
public static void main(String[] args) {
Sub s = new Sub();
System.out.println(s.count);//20
s.display();//20
Base b = s;//多态性
//==:对于引用数据类型来讲,比较的是两个引用数据类型变量的地址值是否相同
System.out.println(b == s);//true
System.out.println(b.count);//10,多态与属性无关
b.display();//20
}
}
6.3.3、练习3
![image-20221130000308491](https://i-blog.csdnimg.cn/blog_migrate/fbaa7f3e773797af25f0e1843f744c1f.png)
【代码实现】
public class InstanceTest {
public static void main(String[] args) {
InstanceTest test = new InstanceTest();
test.method(new Student());
}
public void method(Person e){
//虚拟方法调用
String info = e.getInfo();
System.out.println(info);
//方式一
// if(e instanceof Graduate){
// System.out.println("a graduated student");
// System.out.println("a student");
// System.out.println("a person");
// }else if(e instanceof Student){
// System.out.println("a student");
// System.out.println("a person");
// }else{
// System.out.println("a person");
// }
//方式二
if(e instanceof Graduate){
System.out.println("a graduated student");
}
if(e instanceof Student){
System.out.println("a student");
}
if(e instanceof Person){
System.out.println("a person");
}
}
}
6.3.4、练习4
【代码实现】
public class GeometricObject {
protected String color;
protected double weight;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public GeometricObject(String color, double weight) {
super();
this.color = color;
this.weight = weight;
}
public double findArea(){
return 0.0;
}
}
public class Circle extends GeometricObject {
private double radius;
public Circle(double weight,String color, double radius) {
super(color,weight);
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
@Override
public double findArea() {
return Math.PI * radius * radius;
}
}
public class MyRectangle extends GeometricObject {
private double width;
private double height;
public MyRectangle(double width, double height,String color,double weight) {
super(color, weight);
this.height = height;
this.width = width;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
@Override
public double findArea() {
return width * height;
}
}
/*
定义一个测试类GeometricTest,
编写equalsArea方法测试两个对象的面积是否相等(注意方法的参数类型,利用动态绑定技术),
编写displayGeometricObject方法显示对象的面积(注意方法的参数类型,利用动态绑定技术)
*/
public class GeometricTest {
public static void main(String[] args) {
GeometricTest test = new GeometricTest();
Circle c1 = new Circle(2.3,"white",1.0);//造圆
test.displayGeometricObject(c1);
Circle c2 = new Circle(3.3,"white",1.0);
test.displayGeometricObject(c2);
boolean isEqual = test.equalsArea(c1, c2);
System.out.println("面积是否相等: " + isEqual);
MyRectangle rect = new MyRectangle(2.1, 3.4,"red",1.0);
test.displayGeometricObject(rect);
}
//显示对象的面积
public void displayGeometricObject(GeometricObject o){//多态的使用
System.out.println("面积为: " + o.findArea());
}
//测试两个对象的面积是否相等
public boolean equalsArea(GeometricObject o1,GeometricObject o2){
return o1.findArea() == o2.findArea();
}
}
6.3.5、练习5(面试题)
知识点:
public void add(int a, int... arr)
和public void add(int a, int[] arr)
是重写
public void add(int a, int... arr)
和public void add(int a, int b, int c)
不是重写
写出输出语句结果
public class InterviewTest {
public static void main(String[] args) {
Base base = new Sub();
base.add(1, 2, 3);//输出sub_1
Sub s = (Sub)base;//输出sub_2,优先调用确定多个参数的
s.add(1,2,3);
}
}
class Base {
public void add(int a, int... arr) {
System.out.println("base");
}
}
class Sub extends Base {
//是重写
public void add(int a, int[] arr) {
System.out.println("sub_1");
}
//没用,根本就不是重写
public void add(int a, int b, int c) {
System.out.println("sub_2");
}
}
7、Object 类的使用
java.lang.Object类
- Object类是所有Java类的根父类;
- 如果在类的声明中未使用 extends 关键字指明其父类,则默认父类为 java.lang.Object 类
- Object类中的功能(属性、方法)都具有通用性
- 属性:无
- 方法:
equals()
/toString()
/getClass()
/hashCode()
/clone()
/finalize()
/wait()
、notify()
、notifyAll()
- Object类只声明了一个空参的构造器
7.1、Object类中的主要结构
7.2、== 操作符与equals()方法
回顾 == 的使用
-
运算符
-
可以使用在基本数据类型变量和引用数据类型变量中
-
如果比较的是基本数据类型变量:比较两个变量保存的数据是否相等(不一定类型要相同,boolean除外)
如果比较的是引用数据类型变量:比较两个对象的地址值是否相同,即两个引用是否指向同一个对象实体
补充:== 符号使用时,必须保证符号左右两边的变量类型一致(一致但不一定相同)
equals()方法的使用
-
是一个方法,而非运算符
-
只能适用于引用数据类型
-
Object类中equals()的定义
public boolean equals(Object obj){ return (this == obj); }
-
说明:Object类中定义的equals()和==的作用是相同的,比较两个对象的地址值是否相同,即两个引用是否指向同一个对象实体
-
像String、Date、File、包装类等都重写了Object类中的equals()方法。重写以后,比较的不是两个引用的地址是否相同,而是比较两个对象的 “实体内容” 是否相同
-
通常情况下,我们自定义的类如果使用equals()的话,也通常是比较两个对象的 “实体内容” 是否相同。那么我们就需要对Object类中的equals()进行重写
面试题:==和equals()的区别
import java.sql.Date;
public class EqualsTest {
public static void main(String[] args) {
//*************基本数据类型*************
int i = 10;
int j = 10;
double d = 10.0;
System.out.println(i == j); //true
System.out.println(i == d); //true,有自动类型提升
// boolean b = true;
// System.out.println(i == b);//false,boolean除外
char c = 10;
System.out.println(i == c); //true
char c1 = 'A';
char c2 = 65;
System.out.println(c1 == c2); //true
//*************引用数据类型*************
Customer cust1 = new Customer("Tom" ,21);
Customer cust2 = new Customer("Tom" ,21);
System.out.println(cust1 == cust2); //false
String str1 = new String("atguigu");
String str2 = new String("atguigu");
System.out.println(str1 == str2); //false
System.out.println(cust1.equals(cust2));//false
System.out.println(str1.equals(str2));//true, String类重写了equals()方法
Date date1 = new Date(23432525324L);
Date date2 = new Date(23432525324L);
System.out.println(date1.equals(date2));//true, Date类重写了equals()方法
}
}
重写equals()方法
public class Customer {
private String name;
private int age;
//**********自动生成的equals()**********
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Customer other = (Customer) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
//**********手动实现equals()的重写**********
//重写的原则:比较两个对象的实体内容(即:name和age)是否相同
@Override
public boolean equals(Object obj) {
if (this == obj) {//先比较 当前对象(调用对象) 和 形参对象 是否相同
return true;
}
if(obj instanceof Customer){ //this肯定是Customer的对象,这里判断一下obj是不是Customer的对象
Customer cust = (Customer)obj;
//比较两个对象的每个属性是否都相同
// if(this.age == cust.age && this.name.equals(cust.name)){ //name是String类型
// return true;
// }else{
// return false;
// }
//或
return this.age == cust.age && this.name.equals(cust.name);
}
return false;
}
}
重写equals()方法的原则
- 对称性:如果 x.equals(y) 返回是true,那么 y.equals(x) 也应该返回是true
- 自反性:x.equals(x) 必须返回是true
- 传递性:如果 x.equals(y) 返回是true,而且 y.equals(z) 返回是true,那么z.equals(x)也应该返回是true
- 一致性:如果 x.equals(y) 返回是true,只要x和y内容一直不变,不管你重复 x.equals(y) 多少次,返回都是true
- 任何情况下,x.equals(null)永远返回是false,null.equals(x) 是空指针异常,x.equals (和x不同类型的对象)永远返回是false
判断下列语句输出true还是false
7.3、toString()方法
Object类中 toString() 的使用
-
当我们输出一个引用对象时,实际上就是调用当前对象的toString()
-
Object类中toString的定义方法
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
-
像String、Date、File、包装类等都重写了Object类中的toString()方法,使得在调用toString()时,返回 “实体内容” 信息
-
自定义类也可以重写toString()方法,当调用此方法时,返回对象的 “实体内容”
import java.util.Date;
public class ToStringTest {
public static void main(String[] args) {
Customer cust1 = new Customer("Tom",21);
System.out.println(cust1.toString()); //com.atguigu.java1.Customer@15db9742 --> Customer[name = Tom,age = 21]
System.out.println(cust1); //com.atguigu.java1.Customer@15db9742 --> Customer[name = Tom,age = 21]
String str = new String("MM");
System.out.println(str);//MM, 输出实体内容
Date date = new Date(4534534534543L);
System.out.println(date.toString());//Mon Sep 11 08:55:34 GMT+08:00 2113
}
}
重写toString()方法
public class Customer {
private String name;
private int age;
//**********自动实现toString()的重写**********
@Override
public String toString() {
return "Customer [name=" + name + ", age=" + age + "]";
}
//**********手动实现toString()的重写**********
@Override
public String toString() {
return "Customer [name=" + name + ", age=" + age + "]";
}
}
7.4、练习
7.4.1、练习1
编写Order类,有int型的orderId, String型的orderName
相应的getter()和setter()方法,两个参数的构造器,重写父类的equals()方法:public boolean equals(Object obj)
并判断测试类中创建的两个对象是否相等
【代码实现】
public class OrderTest {
public static void main(String[] args) {
Order order1 = new Order(1001,"AA");
Order order2 = new Order(1001,"BB");
System.out.println(order1.equals(order2)); //false
Order order3 = new Order(1001,"BB");
System.out.println(order2.equals(order3)); //true
}
}
class Order{
private int orderId;
private String orderName;
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public Order(int orderId, String orderName) {
super();
this.orderId = orderId;
this.orderName = orderName;
}
//重写equals()
public boolean equals(Object obj){
if(this == obj){
return true;
}
if(obj instanceof Order){
Order order = (Order)obj;s
return this.orderId == order.orderId && this.orderName.equals(order.orderName);
}
return false;
}
}
7.4.2、练习2
【代码实现】
public class GeometricObject {
protected String color;
protected double weight;
public GeometricObject() {
super();
this.color = "white";
this.weight = 1.0;
}
public GeometricObject(String color, double weight) {
super();
this.color = color;
this.weight = weight;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
}
public class Circle extends GeometricObject{
private double radius;
public Circle() {
super(); //直接调用父类空参构造器即可
// this.color = "white";
// this.weight = 1.0;
this.radius = 1.0;
}
public Circle(double radius) {
super(); //同上
// this.color = "white";
// this.weight = 1.0;
this.radius = radius;
}
public Circle(double radius,String color,double weight) {
super(color,weight);//同上
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
//计算圆的面积
public double findArea(){
return Math.PI * radius * radius;
}
@Override
public boolean equals(Object obj) {
if(this == obj){
return true;
}
if(obj instanceof Circle){
Circle c = (Circle)obj;
return this.radius == c.radius;
}
return false;
}
@Override
public String toString() {
return "Circle [radius=" + radius + "]";
}
}
//写一个测试类,创建两个Circle对象,判断其颜色是否相等;利用equals方法判断其半径是否相等;利用toString()方法输出其半径
public class CircleTest {
public static void main(String[] args) {
Circle circle1 = new Circle(2.3);
Circle circle2 = new Circle(3.3,"white",2.0);//或者new Circle(3.3, new String("white"), 2.0) <---- String类型和对象都是引用数据类型
System.out.println("颜色是否相等:" + circle1.getColor().equals(circle2.getColor()));
System.out.println("半径是否相等: " + circle1.equals(circle2));
System.out.println(circle1);
System.out.println(circle2.toString());
}
}
8、包装类(Wrapper)
8.1、包装类的使用
Java提供了8种基本数据类型对应的包装类,使得基本数据类型的变量具有类的特征
基本数据类型的包装类Byte
、Short
、Integer
、Long
、Float
、Double
、Boolean
、Character
重写了toString(),调用toString()时输出 “实体内容”
注意:其中Byte、Short、Integer、Long、Float、Double的父类是Number类
8.2、基本类型、包装类与String类间的转换
import org.junit.Test;
public class WrapperTest {
//基本数据类型 ---> 包装类:调用包装类的构造器
@Test
public void test1(){
int num1 = 10;
Integer in1 = new Integer(num1);
System.out.println(in1.toString());//10
Integer in2 = new Integer("123");//必须是存数字
System.out.println(in2.toString());//123
//报异常
// Integer in3 = new Integer("123abc");
// System.out.println(in3.toString());
Float f1 = new Float(12.3f);
Float f2 = new Float("12.3");
System.out.println(f1);//12.3
System.out.println(f2);//12.3
Boolean b1 = new Boolean(true);//true
Boolean b2 = new Boolean("true");//true
Boolean b3 = new Boolean("TrUe");//true
System.out.println(b3);
Boolean b4 = new Boolean("true123");
System.out.println(b3);//false
Order order = new Order();
System.out.println(order.isMale);//false
System.out.println(order.isFemale);//null, isFemale是Boolean类型,引用数据类型默认值为null
}
//包装类 ---> 基本数据类型:调用包装类的xxxValue()
@Test
public void test2(){
Integer in1 = new Integer(12);
int i1 = in1.intValue();
System.out.println(i1 + 1);//13
Float f1 = new Float(12.3);
float f2 = f1.floatValue();
System.out.println(f2 + 1);//13.3
}
/*
* JDK 5.0 新特性:自动装箱 与 自动拆箱
*/
@Test
public void test3(){
int num1 = 10;
//举例:
method(num1);//利用自动装箱
//自动装箱:基本数据类型 ---> 包装类
int num2 = 10;
Integer in1 = num2;//自动装箱
boolean b1 = true;
Boolean b2 = b1;//自动装箱
//自动拆箱:包装类--->基本数据类型
int num3 = in1;//自动拆箱
}
public void method(Object obj){//多态
System.out.println(obj);
}
//基本数据类型、包装类 ---> String类型:调用String重载的valueOf(Xxx xxx)
@Test
public void test4(){
int num1 = 10;
//方式1:连接运算
String str1 = num1 + "";
//方式2:调用String的valueOf(Xxx xxx)
float f1 = 12.3f;
String str2 = String.valueOf(f1);//"12.3"
System.out.println(str2);
Double d1 = new Double(12.4);
String str3 = String.valueOf(d1);
System.out.println(str3);//"12.4"
}
//String类型 ---> 基本数据类型、包装类:调用包装类的parseXxx(String s)
@Test
public void test5(){
String str1 = "123";
//可能会报NumberFormatException(String是纯数字不会报错,否则会报错:String str1 = "123a";)
int num2 = Integer.parseInt(str1);
System.out.println(num2 + 1);//124
String str2 = "true";
boolean b1 = Boolean.parseBoolean(str2);
System.out.println(b1);//true
}
}
class Order{
boolean isMale;
Boolean isFemale;
}
下列语句都输出什么
public void test4(){
Integer num = new Integer(1);
System.out.println(num);//1
System.out.println(num.toString());//1
System.out.println(new Integer(1));//1
}
8.3、练习
8.3.1、练习1(面试题)
如下三个 @Test 输出结果是什么?
import org.junit.Test;
public class InterViewTest {
@Test
public void test(){
Object o1= true? new Integer(1) : new Double(2.0);//三元运算符编译的时,数据类型必须统一
System.out.println(o1);//1.0
}
@Test
public void test2(){
Object o2;
if(true)
o2 = new Integer(1);
else
o2 = new Double(2.0);
System.out.println(o2);//1
}
@Test
public void test3() {
Integer i = new Integer(1);
Integer j = new Integer(1);
System.out.println(i == j); //false,引用数据类型比较的是地址,值相同,但地址不相同
//Integer内部定义了一个IntegerCache结构,IntegerCache中定义Integer cache[],保存了从-128-127范围的整数。
//如果我们使用自动装箱的方式,给Integer赋值的范围在-128-127范围内时,可以直接使用数组中的元素,不用再去new了。目的是提高效率
Integer m = 1;
Integer n = 1;
System.out.println(m == n);//true
Integer x = 128;//相当于new了一个Integer对象
Integer y = 128;//相当于new了一个Integer对象
System.out.println(x == y);//false
}
}
8.3.2、练习2
【代码实现】
import java.util.Scanner;
import java.util.Vector;
public class ScoreTest {
public static void main(String[] args) {
//1.实例化Scanner,用于从键盘获取学生成绩
Scanner scan = new Scanner(System.in);
//2.创建Vector对象:Vector v=new Vector();相当于原来的数组
Vector v = new Vector();
//3.通过for(;;)或while(true)方式,给Vector中添加数据
int maxScore = 0;
for(;;){
System.out.println("请输入学生成绩(以负数代表输入结束)");
int score = scan.nextInt();
//3.2 当输入是负数时,跳出循环
if(score < 0){
break;
}
if(score > 100){
System.out.println("输入的数据非法,请重新输入");
continue;
}
//3.1 添加操作:v.addElement(Object obj)
//jdk5.0之前:
// Integer inScore = new Integer(score);
// v.addElement(inScore);//多态
//jdk5.0之后:
v.addElement(score);//自动装箱 new Integer(score)
//4.获取学生成绩的最大值
if(score > maxScore){
maxScore = score;
}
}
//5.遍历Vector,得到每个学生的成绩,并与最大成绩比较,得到每个学生的等级。
char level = 0;
for(int i = 0;i < v.size();i++){
Object obj = v.elementAt(i);
Integer inScore = (Integer)obj;//向下转型
//jdk 5.0之前:
// int score = inScore.intValue();
//jdk 5.0之后:
int score = inScore;
if(maxScore - score <= 10){
level = 'A';
}else if(maxScore - score <= 20){
level = 'B';
}else if(maxScore - score <= 30){
level = 'C';
}else{
level = 'D';
}
System.out.println("student-" + i + " score is " + score + ",level is " + level);
}
}
}
物竞天择,适者生存,加油吧!!!