Java第二次實驗

1.定義一個表示學生的student類,包括的域有學號、姓名、性別、年齡,包括的方法有獲得學號、姓名、性別、年齡及修改年齡。編寫Java程序創建student類的對象及測試其方法的功能.

2.爲第1題的student類定義構造函數初始化所有的域,增加一個方法public String printInfo()把student類對象的所有域信息組合形成一個字符串,並在主類中創建學生對象及測試各方法的功能.

3.設計一個Point類,該類包含兩個int型成員變量:x、y,一個color型成員變量mycolor,請給出此類的構造方法,分別是一個不帶參數的,一個帶兩個參數的,一個帶三個參數的構造方法。用下面的main方法測試:

public static void main(String[] args)

{

Point A=new Point();

Point B=new Point(50,60);

Point C=new Point(100,200,Color.red);

System.out.println(“B:(”+B.getX()+”,”+B.getY()+”)”+”color: “+B.getColor());

A.setX(100);

A.setY(200);

A.setColor(Color.red);

System.out.println(“A==B?”+A.equals(B));

}


程序代碼:

(1,2)

public class StudentTest {

public static void main(String[] args) {
Student stu=new Student(1001,"李明","男",23);
System.out.println(stu.printInfo());

stu.alerAge(25);
System.out.println(stu.printInfo());

}

}


class Student
{
private int id;
private String name;
private String sex;
private int age;

public Student(int id,String name,String sex,int age)
{
this.id=id;
this.setName(name);
this.setSex(sex);
this.setAge(age);
}

public void setName(String name)
{
if(name==null||name=="")
this.name="姓名未知";
else
this.name=name;
}

public void setSex(String sex)
{
if(sex=="男"||sex=="女")
this.sex=sex;
else
this.sex="輸入錯誤 !";
}
public void setAge(int age)
{
if(age>0&&age<100)
this.age=age;
else
this.age=0;
}

public int getId()
{
return id;
}

public String getName()
{
return name;
}

public String getSex()
{
return sex;
}

public int alerAge(int age1)
{
this.age=age1;
return this.age;
}

public String printInfo()
{
return "我的信息:"+"\n"+"學號:"+id+" 姓名:"+name+" 性別:"+sex+" 年齡"+age;
}
}


3.import java.awt.Color;
public class Point {
int x;
int y;
Color mycolor;

public Point()
{
this(0,0,Color.black);
}

public Point(int x,int y)
{
this.setX(x);
this.setY(y);
}
public Point(int x,int y,Color mycolor)
{
this.setX(x);
this.setY(y);
this.setColor(mycolor);
}
public void setX(int x)
{
this.x=x;
}

public void setY(int y)
{
this.y=y;
}

public void setColor(Color mycolor)
{
this.mycolor=mycolor;
}

public int getX()
{
return x;
}

public int getY()
{
return y;
}

public Color getColor()
{
return mycolor;
}
public static void main(String[] args) {
Point A=new Point();

Point B=new Point(50,60);

// Point C=new Point(100,200,Color.red);

System.out.println("B:("+B.getX()+","+B.getY()+")"+"color: "+B.getColor());

A.setX(100);

A.setY(200);

A.setColor(Color.red);

System.out.println("A==B?"+A.equals(B));

}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章