JAVA---尚学堂---第五章作业答案(编程题2)

package HomeWork;

import java.util.Scanner;

/**
 * 2. 编写程序实现乐手弹奏乐器。乐手可以弹奏不同的乐器从而发出不同的声音。可以弹奏的乐器包括二胡、钢琴和琵琶。

      实现思路及关键代码:

      1) 定义乐器类Instrument,包括方法makeSound();

      2) 定义乐器类的子类:二胡Erhu、钢琴Piano和小提琴Violin;

      3) 定义乐手类Musician,可以弹奏各种乐器play(Instrument i);

      4) 定义测试类,给乐手不同的乐器让他弹奏。
 * @author lenovo
 *
 */
public class HomeWork02 {
    public static void main(String[] args) {
        boolean flag = true;
        
        Erhu e = new Erhu();
        Pinao p = new Pinao();
        Violin v = new Violin();
        Musician m = new Musician();

        Scanner scanner = new Scanner(System.in);
        while(flag){
            System.out.println("########################");
            System.out.println("请按对应的数字选择演奏的乐器类型:");
            System.out.println("0--二胡");
            System.out.println("1--钢琴");
            System.out.println("2--小提琴");
            int type = scanner.nextInt();
            
            if(type==0){
                m.play(e);
            }
            if(type==1){
                m.play(p);
            }
            if(type==2){
                m.play(v);
            }
            
            System.out.println("可以按任意数字继续!");

            int s = scanner.nextInt();
            if(s == 9){
                
            }

        }
                
    }

}

//乐器类
abstract class Instrument {
    String name;
    String sound;
    
    abstract String makesound();
    
}

//二胡乐器子类
class Erhu extends Instrument {
    Erhu(){
        this.name = "二胡";
        this.sound = "正在演奏二胡声!";
    }
    
    String makesound(){
        return this.sound;
    }


    
    
}

//钢琴乐器子类
class Pinao extends Instrument {
    Pinao(){
        this.name = "钢琴";
        this.sound = "正在演奏钢琴声!";
    }
    
    String makesound(){
        return this.sound;
    }
    
}

//小提琴乐器子类
class Violin extends Instrument {
    Violin(){
        this.name = "小提琴";
        this.sound = "正在演奏小提琴声!";
    }
    
    String makesound(){
        return this.sound;
    }
    
}

//乐手类
class Musician {
    void play(Instrument i){
        
        System.out.println(i.makesound());
    }
    
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值