资源描述
实验一 Java面向对象基础、数组 实验报告一、实验目的1. 理解面向对象编程基本思想2. 了解类的封装方法,以及如何创建类和对象3. 掌握面向对象程序设计的方法,了解类的继承性和多态性的作用4. 掌握 Java 中的数组定义、引用二、实验要求编写程序时要注意体现面向对象思想,体会不同访问控制符的作用。1. 编写一个Vehicle类和它的二个子类Bus类和Boat类。(要求:程序要有构造方法重载;要能体现类的多态性)2. 定义一个由若干个整数组成的数组,要求输出该数组的平均值以及所有的奇数之和。3. 随机生成30个0-9之间的数字,分别统计0-9这10个数字分别出现了多少次。三、实验内容及结果1. 编写一个Vehicle类和它的二个子类Bus类和Boat类。public class Vehicle private String color;public Vehicle() this(black);public Vehicle(String color) this.color = color;public String toString() return this is a + this.color + vehicle;class Bus extends Vehicle private int passagerNumber;public Bus() this(50, black);public Bus(int number) this(number, black);public Bus(int number, String color) super(color);this.passagerNumber = number;public String toString() return super.toString().replace(vehicle, bus)+ , max passager number: + this.passagerNumber;class Boat extends Vehicle private String owner;public Boat() super(black);this.owner = nobody;public Boat(String owner) super(black);this.owner = owner;public Boat(String owner, String color) super(color);this.owner = owner;public String toString() return super.toString().replace(vehicle, boat)+ own by + this.owner;2. 定义一个由若干个整数组成的数组,要求输出该数组的平均值以及所有的奇数之和。import java.util.Random;public class Experiment02 public static void main(String args) Random r = new Random(System.currentTimeMillis();int nums = new int10;for (int i = 0; i 10; i+) numsi = r.nextInt(100);System.out.print(i != 0 ? , : ) + numsi);System.out.println();System.out.println(平均数: + getAverage(nums);System.out.println(奇数和: + evenTotal(nums);public static int evenTotal(int numbers) int sum = 0;for (int i = 0; i numbers.length; i+) sum += (numbersi % 2 != 0 ? numbersi : 0); return sum;public static double getAverage(int numbers) int sum = 0;for (int i = 0; i numbers.length; i+) sum += numbersi;return sum * 1.0 / numbers.length;运行结果:(每次运行结果不一样)3. 随机生成30个0-9之间的数字,分别统计0-9这10个数字分别出现了多少次。import java.util.Random;public class Experiment03 public static void main(String args) Random r = new Random(System.currentTimeMillis();int nums = new int10;int count = new int10;for (int i = 0; i 10; i+) numsi = r.nextInt(10);countnumsi+;for (int i = 0; i 10; i+) System.out.println(数字 + i + 的出现次数为: + counti);运行结果(每次运行结果不一样):
展开阅读全文