早上起来得早,便逛了下论坛,然后看到现在论坛上现在越来越多人为了技术分不断提问...
提的还都是百度里一些比较老的练习题类,我对这种做法总是不赞同的.但是看到了问题,总有些想做做的冲动.
我测试过,结果是正确的.但感觉有些问题,由于要开始入学测试了,也没有时间去优化了,发出来大家交流一下.- public class example1 {
- /*老伯伯要带鱼、狗、猫过河到
- 对岸.,有一条船,只能坐一个人,
- 老伯每次只能带一样动物过河,当
- 老伯不在的时侯狗会咬猫,猫会吃
- 鱼,鱼会跳下河,请问怎么顺序过河呢?要求:编
- 写程序,由程序来推出过河的顺序*/
- public static void main(String[] args) {
- Animal animal =Animal.CAT;
- River river=new River();
- while(!(river.getCount()==3)){
- river.Cross(animal);
- animal=animal.nextAnimal();
- }
- System.out.println("安全过河了泥沙河,oh year!");
- }
- }
- enum Animal{
- FISH,CAT,DOG,BOSS;
- public boolean animalDie(String coexist){
- if(this.toString()=="鱼"&&coexist=="猫"||this.toString()=="猫"&&coexist=="鱼")
- return false;
- else if(this.toString()=="猫"&&coexist=="狗"||this.toString()=="狗"&&coexist=="猫")
- return false;
- else return true;
- }
- public Animal nextAnimal(){
- switch(this){
- case FISH:
- return CAT;
- case CAT:
- return DOG;
- case DOG:
- return FISH;
- }
- return null;
- }
- public String toString(){
- switch(this){
- case FISH:
- return "鱼";
- case CAT:
- return "猫";
- case DOG:
- return "狗";
- }
- return null;
- }
- }
- class River{
- private Animal animal;
- private String[] animalName=new String[3];
- private int count=0;
- public void Cross(Animal ail){
- animal=ail;
- System.out.println(ail.toString()+"兄过河啦!");
- if(count<3){//避免角标越界
- animalName[count]=ail.toString();
- System.out.println(animalName[count]);
- }
- if(bank()==true);
- count++;
- }
- public boolean bank(){
- System.out.print("现在河对岸有"+(count+1)+"只动物:");
- for(int i=0;i<count+1;i++)
- System.out.print(animalName[i]+" ");
- System.out.println();
- if(count==1){
- if(!(animal.animalDie(animalName[0]))){
- System.out.println("尼玛"+animal.toString()+"与"+animalName[0]+"打架啦!");
- System.out.println(animalName[0]+"被带回去了!");
- animalName[0]=animal.toString();
- count--;
- return false;
- }
- }
- return true;
- }
- public int getCount() {
- return count;
- }
-
- }
复制代码 |
|