(完整版)Java程序设计实验报告 下载本文

内容发布更新时间 : 2024/5/23 17:00:55星期一 下面是文章的全部内容请认真阅读。

Java程序设计实验报告

实验一

实验题目:从键盘上读入10个字符串存入数组a中,然后输出这

10个字符串中最大字符串和最小字符串。

实验代码:

public class StrPro {

public static void main(String[] args) { String str[] = new String[5];

System.out.println(\:\); int i;

String max,min; for(i=0;i<5;i++){

System.out.print(\+(i+1)+\); Scanner sc = new Scanner(System.in); str[i] = sc.nextLine(); }

max = str[0]; min = str[0];

for(i=0;i

if(max.compareTo(str[i])<0){ max = str[i]; }

if(min.compareTo(str[i])>0){ min = str[i]; } }

System.out.println(\最大的字符串为:\+max); System.out.println(\最小的字符串为:\+min); } }

实验结果:

实验心得体会:

掌握了java的基本语法,数组的定义与使用,做这个实验要了

解字符串数组的定义及字符串数组的输入方法,还有比较字符串数组的大小的调用方法等。

实验二

实验题目:

自定义一个矩形类(Rectangle),包含的属性有:长(length),宽(width),包含的方法有:关于属性的setter和getter方法,即setLength,getLength,setWidth,getWidth,计算矩形面积的方法(getArea)。

定义矩形类的子类正方形类(Square),包含的属性和方法自行确定,要求完成的功能是,能计算正方形的面积。

定义一个测试类(Test),测试矩形类和正方形类能否正确的计算面积。

以上类中属性和方法的访问权限自行确定,方法和构造方法若有参数,也自行确定。

实验代码:

public class Rectangle { int Length;

int Width;

public int getLength() { return Length; }

public void setLength(int length) { Length = length; }

public int getWidth() { return Width; }

public void setWidth(int width) { Width = width; }

int getArea(){

return Length * Width; } }

public class Square extends Rectangle{ Square(int border) {

super.setLength(border); super.setWidth(border); } }

public class Test { public void test(){

System.out.println(\请选择计算的形状的序号:1.矩形 2.正方形\); Scanner sc = new Scanner(System.in); int i = sc.nextInt(); int len,wid; if(i==1){

System.out.print(\请输入矩形的长:\); Scanner s = new Scanner(System.in); len = s.nextInt();

System.out.print(\请输入矩形的宽:\); wid = s.nextInt();

Rectangle re = new Rectangle(); re.setLength(len); re.setWidth(wid);

System.out.println(\矩形面积为:\+re.getArea()); }

else if(i==2){

System.out.print(\请输入正方形的边长:\);

}

Scanner s = new Scanner(System.in); len = s.nextInt();

Square sq = new Square(len);

System.out.println(\正方形面积为:\+sq.getArea()); } else{

System.out.println(\输入错误!\); } }

public static void main(String[] args) { new Test().test(); }

实验结果:

实验心得体会:

做这个实验要掌握如何定义类以及类的成员变量、类的方法,学会对象的创建、对象属性的引用和方法的调用以及如何定义和使用构造方法。掌握this的使用以及派生子类的方法,理解关键字super的含义。理解继承中属性的隐藏和方法的覆盖机制,理解在继承关系中构造方法的调用过程。

实验三

实验题目:定义一个Student类,包含姓名(name)、身高(height)、

体重(weight),以及talk()方法,该方法的功能是,输出自己的身高和体重信息。

Student类实现Comparable接口,实现按照体重的大小比较两个Student对象的大小。

最后,定义一个测试类,生成一个数组,该数组有6个元素,每个元素类型是Student,调用Arrays.sort方法对该数组排序。

实验代码:

public class Student implements Comparable { private String name;

private float height, weight;

public Student(String name, float height, float weight) { super();

this.name = name; this.height = height; this.weight = weight; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public float getHeight() { return height; }

public void setHeight(float height) { this.height = height; }

public float getWeight() { return weight; }

public void setWeight(float weight) {