本帖最后由 bigbean 于 2014-3-6 00:06 编辑
- package com.itheima;
- /*
- 一位老农带着猫、狗、鱼过河,河边有一条船,每次老农只能带一只动物过河。
- 当老农不和猫狗鱼在一起时,狗会咬猫,猫会吃鱼,当老农和猫狗鱼在一起时,
- 则不会发生这种问题。编程解决猫狗鱼过河问题。
- 需求分析:狗会咬猫,猫会吃鱼
- 步骤:
- 1.先将猫拿过去
- 2.将鱼(狗)拿过去,不过要带着猫回来
- 3.放下猫,再带着狗(鱼)过去
- 4.最后带着猫过去
- */
- class PassRiver
- {
- String thisway =new String();
- String thatway =new String();
- String boxi=new String();
- String boxa=new String();int x ,y,time;
- boolean locate =true;
- String all[]={"猫","狗","鱼","老农"};
-
- PassRiver()
- {
- thisway="猫狗鱼老农";
- thatway="";
- }
-
- void re(){
- thisway= boxi;
- thatway=boxa;
- }
-
- String go(String str)
- {
- if(locate=true)
- {
- thisway=thisway.replace(str, "");
- thatway=thatway.concat(str);
- thisway=thisway.replace("老农", "");
- thatway=thatway.concat("老农");
- }
- else if(safe()){ System.out.println("农夫带着"+str+"去对面了,这边还剩下"+thisway);}
- else re();
- y++;locate=false;
- return str;
-
- }
-
- String back(String str)
- {
- if(locate=false)
- {
- thatway=thatway.replace(str, "");
- thisway=thisway.concat(str);
-
- thatway=thatway.replace("老农", "");
- thisway=thisway.concat("老农");
- }
- else if(safe()){
- System.out.println("农夫带着"+str+"回来了");}//这边有:"+thisway+",那边还剩下:"+thatway
- else {System.out.println("农夫空手回来了,这边有:"+thisway+",那边还剩下:"+thatway) ;re();};y++;
- locate=false; return str;
- }
- boolean safe()//判断动物是否安全
- { boolean sa;
- sa=judge(thisway)&&judge(thatway);
- if(sa);
- else re();
- return sa;
- }
-
- String printState()//输出状态方法
- {
- String ps="现在本岸有:"+thisway+"\n对岸有:"+thatway;//
- return ps;
- }
-
-
- void play()//开始过河
- //{ while((thatway.contains("猫")&&thatway.contains("鱼")&&thatway.contains("狗")&&thatway.contains("老农"))==false)
- {//System.out.println("1"+printState());
- System.out.println("农夫,猫,鱼,狗都在这边,开始过河.\n");
- while(thisway.contains(all[1])
- || thisway.contains(all[2])
- ||thisway.contains(all[0])||thisway.contains(all[3]))
- {// System.out.println("2"+printState());
- //System.out.println("88");
- while(locate&&thisway.contains(all[x])&safe())
- {x=y%4;
- System.out.println(time+printState());
- go(all[x]);
-
- System.out.println("333"+printState()); y++;
- }
- while((locate==false)&&thatway.contains(all[x])&safe())
- { x=y%4;
- // System.out.println("4"+printState());
- back(all[x]);
- System.out.println("444"+printState()); y++;
- }
-
- }
- //if(locate)locate=false;else locate=true;
- }
- //}
- Boolean judge(String str)
- {
- if(str.contains("老农"))
- {
- return true;
- }
- else if(str.contains("猫")&str.contains("鱼"))
- {
- return false;
- }
- else if(str.contains("猫")&str.contains("狗"))
- {
- return false;
- }
- return true;
- }
- }
- public class Test10 {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- PassRiver aa=new PassRiver();
- aa.play();
-
- System.out.println(aa.printState());
- }
- }
复制代码 求助啊,面试题最后一题做不出来啊!!!做了半天做了个死循环出来啊!!!
|