1.编写出一个通用的人员类(Person),该类具有姓名(Name)、年龄(Age)、性别(Sex)等域。然后对person类的继承得到一个学生类(Student),该类能够存放学生的5门课的成绩,并能求出平均成绩。最后在Main函数中对student类的功能进行验证。
import java.util.Scanner;
class Person {
String name;
int age;
String sex;
public Person() {}
public Person(String name,int age,String sex) {
this.name=name;
this.age=age;
this.sex=sex;
}
}
class Student extends Person{
int score[]=new int[5];
public Student() {
}
public Student(String name,int age,String sex) {
super(name,age,sex);
score();
}
public void score() {
Scanner sc=new Scanner(System.in);
System.out.println("请输入五门课的成绩:");
for(int i=0;i<score.length;i++) {
score[i]=sc.nextInt();
}
}
public void getAvg() {
int sum=0;
for(int i=0;i<score.length;i++) {
sum+=score[i];
}
float avg=sum/score.length;
System.out.println(this.name+"同学的平均成绩是:"+avg);
}
}
public class Test_avg {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student s=new Student("张三",23,"男");
s.getAvg();
}
}
import java.util.Scanner;
class Hero{
String name;
int vitality;
int grade;
public Hero() {
this.vitality=100;
this.grade=1;
nameInput();
show();
}
public void nameInput() {
Scanner sc=new Scanner(System.in);
System.out.println("请输入英雄的名字:");
name=sc.nextLine();
}
public void show() {
System.out.println("姓名:"+name+"\n生命值:"+vitality+"\n等级"+grade);
System.out.println();
}
public Hero(int type) {
nameInput();
if(type==1) {
this.vitality=100;
System.out.println("普通英雄创建成功");
}else if(type==2) {
this.vitality=200;
System.out.println("高级英雄创建成功");
}
this.grade=1;
show();
}
public void combat(Hero hero) {
hero.vitality-=100;
System.out.println(hero.name+"受到攻击,生命值减100");
hero.show();
}
public void conbat(Hero hero,int type) {
if(type==1) {
hero.vitality-=50;
System.out.println(hero.name+"受到轻度攻击,生命值减50");
}else if(type==2) {
hero.vitality-=80;
System.out.println(hero.name+"受到轻度攻击,生命值减80");
}else {
hero.vitality-=100;
System.out.println(hero.name+"受到轻度攻击,生命值减100");
}
hero.show();
}
}
public class Text_hero {
public static void main(String[] args) {
// TODO Auto-generated method stub
Hero h=new Hero();
Hero h1=new Hero();
h.combat(h1);
h.conbat(h1, 2);
}
}