一、例题1
按照下列要求编写程序
(1)创建一个Rectangle类,添加width和heigth两个成员变量
(2)在Rectangle中添加两种方法分别计算矩形的周长和面积
(3)编程利用Rectangle输出一个矩形的周长和面积
代码如下:
public class Rectangle {
float width, height;
public rectangle(float width, float height) {
this.width = width;
this.height = height;
}
public float getlength() {
return (this.width + this.height) * 2;
}
public float getArea() {
return this.width * this.height;
}
public static void main (String [] args) {
rectangle rect = new Rectangle (10,20);
System.out.println("周长是:" + rect.getLength());
System.out.println("面积是:" + rect.getArea());
}
}
二、例题2
按照下列要求编写程序
(1)编写Animal接口,接口中声明run()方法
(2)定义Bie类和Fish类和实现Animal接口
(3)编写Bied类和Fish类的测试程序,并调用其中的run()方法
代码如下:
public interface Animal {
void run();
}
class Bird implements Animal {
public voidi run(){
System.out.println("鸟儿在飞...");
}
}
class Fish implemnts Animal {
public void run() {
System.out.println("鱼儿在游...");
}
}
public class TestAnimal {
public static void main(String[] args) {
Bird birs = new Bird();
bird.run();
Fish fish = new fish();
fish.run();
}
}
三、例题3
题目:某公司开发部5名开发人员,要进行项目进展汇报演讲,现采取随机排名后进行汇报,请先依次录入5名员工的工号,然后展示出一组随机的排列顺序。
代码如下:
public class Text3{
public static void main(String[] args){
// 定义一个动态初始化数组用于存储5名员工工号
int[] codes = new int[5];
// 提示用户录入5名员工的工号
Scanner sc = Scanner(System.in);
for (int i = 0; i < codes.length; i++){
System.out.println("请你输入第" + (i + 1) + "个员工的工号:");
codes[i] = code;
}
// 打乱数组中的元素数据
Random r = new Random();
for (int i = 0; i < codes.length; i++) {
// codes[i]
// 每遍历到一个数据,都随机一个数组索引范围内的值
// 然后将当前遍历的数据与该索引处的值交换
int index = r.next(codes.length);
// 定义一个变量记住index位置处的值
int temp = codes[index];
// 把i位置处的值赋值给index位置处
codes[index] = codes[i];
// 把intex位置原来的值赋值给i位置处
codes[i] = temp;
}
for (int i = 0; i < codes.length; i++){
System.out.println(codes[i] + " ");
}
}
}