1.学生类
定义一个学生类,设计私有数据成员:
年龄 int age;
姓名 string name;
共有成员函数:
带参数的初始化函数 Input(int a, string str);
获取数据成员函数 Output();
在主函数中定义一个有3个元素的对象数组并分别输入,然后输出对象数组的信息。
import java.util.Scanner; public class Student { private int age; private String name; public void input(int a,String str) { this.age=a; this.name=str; } public void output() { System.out.println(this.age+" "+this.name); } public static void main(String[] args) { Scanner in=new Scanner(System.in); Student stu[]=new Student[3]; for(int i=0;i<stu.length;i++) { System.out.print("请输入第"+(i+1)+"同学的年龄和姓名:"); stu[i]=new Student(); int age=in.nextInt(); String name=in.next(); stu[i].input(age, name); } System.out.println("学生信息:"); for(int i=0;i<stu.length;i++) { stu[i].output(); } } }
2.点类
先定义一个点类,类名为point,将其坐标定义为私有成员,定义五个共有成员函数完成点的输入、输出、返回x坐标、返回y坐标和返回z坐标。在主程序中定义该类的一个对象,做到能够输入坐标,输出坐标,并且输出到原点的距离。
import java.util.Scanner; public class Point { private double x; private double y; private double z; public void input() { System.out.print("请輸入三維点坐标:"); Scanner in=new Scanner(System.in); this.x=in.nextDouble(); this.y=in.nextDouble(); this.z=in.nextDouble(); } public void output() { System.out.print("("+x+","+y+","+z+")"); } public double getX() { return this.x; } public double getY() { return this.y; } public double getZ() { return this.z; } public static void main(String[] args) { Point p=new Point(); double distance; p.input(); distance=Math.sqrt(p.getX()*p.getX()+p.getY()*p.getY()+p.getZ()*p.getZ()); System.out.print("三维点坐标"); p.output(); System.out.print("到原点的距离是:"); System.out.printf("%-10f",distance); } }
3.线段类
构造线段类line,其中私有数据成员为两个point对象(线段的起始点和终点),一个函数输入两个point类型数据成员,一个函数计算线段的长度。在主函数中调用line的两个共有函数完成点的输入和线段长度的输出。
import java.util.Scanner; public class Line { private Point sp = new Point(); private Point ep = new Point(); public void input() { System.out.println("请输入线段的起点和终点坐标:"); sp.input(); ep.input(); } public double lineDis() { return Math.sqrt( (sp.getX() - ep.getX()) * (sp.getX() - ep.getX()) + (sp.getY() - ep.getY()) * (sp.getY() - ep.getY()) + (sp.getZ() - ep.getZ()) * (sp.getZ() - ep.getZ())); } public static void main(String[] args) { Line l = new Line(); l.input(); System.out.printf("线段长度为:%-10f", l.lineDis()); } } class Point { private double x; private double y; private double z; public void input() { System.out.print("请輸入三維点坐标:"); Scanner in = new Scanner(System.in); this.x = in.nextDouble(); this.y = in.nextDouble(); this.z = in.nextDouble(); } public void output() { System.out.print("(" + x + "," + y + "," + z + ")"); } public double getX() { return this.x; } public double getY() { return this.y; } public double getZ() { return this.z; } }