搜档网
当前位置:搜档网 › 实验二 类和对象

实验二 类和对象

实验二:类和对象

姓名:钟铖强班级:计算机13-1 学号:130********

实验目标:

熟悉Eclipse的使用,熟悉Java基础语法,撑握Java类与对象的建立及使用。

实验内容:

编写一个表示二维平面上点的类MyPoint,满足以下条件:

(1)定义private的成员变量x和y,类型为整数。

(2)定义两个MyPoint的构造方法,一个构造方法不带参数,且x和y的初始值为0;另一个构造方法有两个参数,参

数名为x和y,类型为整数,用这两个参数分别初始成员

变量x和y。

(3)定义一个getD方法,功能为返回两个坐标点的(由MyPoint 定义)的距离,值为double类型。

(4)编写main方法,打印坐标(3,2)到坐标(4,5)的距离。

(5)对main方法进行改进,输入任何两个点,并把两个点的距离输出。

实验代码:

//MyPoint

package Ex1;

import https://www.sodocs.net/doc/8a6151894.html,ng.*;

public class MyPoint {

private int x;

private int y;

public MyPoint(){

x=0;

y=0;

}

public MyPoint(int x,int y){

this.x=x;

this.y=y;

}

public static double getD(MyPoint p1,MyPoint p2){

double d1=Math.pow(p2.x-p1.x, 2)+Math.pow(p2.y-p1.y, 2);

double d2=Math.pow(d1,0.5) ;

return d2;

}

}

//主函数

package Ex1;

public class test {

public static void main(String[] args) {

MyPoint p1=new MyPoint(2,3);

MyPoint p2=new MyPoint(4,5);

double d=MyPoint.getD(p1,p2);

System.out.println(d);

}

}

//用户输入主函数

package Ex1;

import javax.swing.JOptionPane;

public class test2 {

public static void main(String[] args) {

String str1 = JOptionPane.showInputDialog("第一个坐标的x:");

String str2 = JOptionPane.showInputDialog("第一个坐标的y:");

String str3 = JOptionPane.showInputDialog("第二个坐标的x:");

String str4 = JOptionPane.showInputDialog("第二个坐标的y:");

int x1 = Integer.parseInt(str1);

int y1 = Integer.parseInt(str2);

int x2 = Integer.parseInt(str3);

int y2 = Integer.parseInt(str4);

MyPoint p1 =new MyPoint(x1,y1);

MyPoint p2=new MyPoint(x2,y2);

double d=MyPoint.getD(p1,p2);

System.out.println(d);

}

}

实验结果:

实验报告:

本次试验主要运用了类与对象的知识,通过定义成员变量,构造方法等操作让试验完成,在实验过程中遇到了一些问题,在老师和同学的帮助下得以解决。另外还有一个不懂的地方,为什么要把getD 设为静态?

相关主题