Java 之 实验七 -- 类和对象
实验七
类和对象
练习一 Dog
设计并实现类Dog,所包含的实例数据表示狗的名字和年龄。定义Dog构造方法接收和初始化实例数据,并定义获取与设置名字和年龄的方法。定义一个方法计算并返回狗等效于人的年龄(狗的实际年龄乘以7)。定义toString方法返回一行描述狗的字符串。创建一个驱动类Kennel,该类的main方法实例化并更新若干个Dog对象。
Dog.java
package J07;
public class Dog{
private String dogName;
private int age;
public Dog(){
}
public Dog(String dogName,int age){
this.dogName = dogName;
this.age = age;
}
public String GetDogName(){
return dogName;
}
public int GetAge(){
return age;
}
public void Setname(String dogName) {
this.dogName = dogName;
}
public void Setage(int age) {
this.age = age;
}
public int toHumanAge(){
return age*7;
}
public String toString(){
return "dog's name:"+dogName+",dog's age:"+age+",people's age:"+toHumanAge();
}
}
DogDemo.java
package J07;
public class DogDemo {
public static void main(String[] arge){
Dog dog = new Dog();
dog.Setname("sheshao");
dog.Setage(3);
System.out.println(dog.toString());
Dog dog1 = new Dog("gougou",5);
System.out.println(dog1.toString());
}
}
练习二 the Coin
编写一段程序,连续投掷硬币100次,查找并记录连续为HEAD的投掷次数的最大值。程序框架如Runs.java所示。具体步骤如下:
- 创建一个coin对象;
- 在循环语句中,使用flip方法投掷硬币,使用getFace方法查看结果是否为HEADS。记录当前连续投掷结果为HEADS的次数,并记录其中的最大值。
- 在循环结束后打印最大值结果。
Coin.java
package J07;
public class Coin {
public final int HEADS = 0;
public final int TAILS = 1;
private int face;
public Coin(){
flip();
}
public void flip(){
face = (int)(Math.random()*2);
}
public boolean isHeads(){
return (face == HEADS);
}
public String toString(){
String faceName;
if (face == HEADS){
faceName = "Heads";
}else{
faceName = "Tails";
}
return faceName;
}
}
Run.java
package J07;
public class Runs {
public static void main(String[] args) {
final int FLIPS = 100;
int currentRun = 0;
int maxRun = 0;
// Create a coin object
Coin coin = new Coin();
//Flip the coin FLIPS times
for(int i =0;i<FLIPS;i++){
//FLIP the coin print the result
coin.flip();
if(coin.isHeads()){
currentRun++;
}else{
currentRun = 0;
}
//update the run information
if(currentRun>=2 &¤tRun >maxRun){
maxRun = currentRun;
}
}
// pring the results
System.out.println(maxRun);
}
}
练习三 格式化输出
文件Deli.java是一个不完整的程序。该程序用于计算在deli购买物品的费用。将该程序保存至本地磁盘,并进行以下操作:
- 阅读并理解程序;
- 添加import语句,导入DecimalFormat和NumberFormat两个类;
- 声明变量money为一个NumberFormat类型的对象;
- 声明变量fmt为一个DecimalFormat类型的对象;
- 按照下面的格式打印结果。使用格式化对象money打印price和total price,使用格式化对象fmt打印weight。



浙公网安备 33010602011771号