- 论坛徽章:
- 0
|
程序的开发步骤:
1.根据需求定义所要的类
2.根据题目中的要求规划出类的属性
3.所有的属性必须封装:private
4.所有的属性必须通过getter和setter访问
5.如果需要增加构造方法,为属性赋值
6.所有的信息不要在类中直接输出,而是交给调用处输出
|-在类中不能出现System.out.println()语句。
范例:
要求设计一个学生的类,里面有学生的三项成绩:计算机成绩、数学成绩、英语成绩
要求可以求总分、平均分、最高分、最低分,并且可以输出一个学生的完整信息。
类Student代码如下:
public class Student {
private String name;
private int age;
private float computer;
private float math;
private float english;
public Student(String n,int a,float c,float m,float e){
this.setAge(a);
this.setName(n);
this.setComputer(c);
this.setEnglish(e);
this.setMath(m);
}
public float sum(){ //求总分
return getComputer()+getEnglish()+getMath();
}
public float avg(){ //求平均分
return this.sum()/3;
}
public float max(){ //求最高分
float max=computer>math?computer:math;
max=max>english?max:english;
return max;
}
public float min(){ //求最低分
float min=computerenglish?computer:english;
min=minmath?min:math;
return min;
}
public String print(){
return "学生信息:\n"+getName()+"、"+getAge()
+"\n"+getComputer()+"、"+getEnglish()+"、"+getMath();
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getComputer() {
return computer;
}
public void setComputer(float computer) {
this.computer = computer;
}
public float getEnglish() {
return english;
}
public void setEnglish(float english) {
this.english = english;
}
public float getMath() {
return math;
}
public void setMath(float math) {
this.math = math;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
类ExecDemo代码如下:
public class ExecDemo {
public static void main(String[] args) {
Student stu =new Student("张三",21,90.4f,99f,67f);
System.out.println(stu.print());
System.out.println("最高分:"+stu.max());
System.out.println("最低分:"+stu.min());
System.out.println("平均分:"+stu.avg());
}
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/106716/showart_2137182.html |
|