• 大小: 3KB
    文件类型: .rar
    金币: 1
    下载: 0 次
    发布日期: 2021-05-18
  • 语言: Java
  • 标签: 过河  

资源简介

农夫过河问题,农夫带着狼,羊,狗,要从此岸到达比岸,该怎样走呢?

资源截图

代码片段和文件信息

import java.util.Iterator; 
import java.util.linkedList; 

public class AcrossTheRiver {     
// 定义三个String对象
public static final String sheepName = “羊“; 
public static final String wolfName = “狼“; 
public static final String cabbageName = “白菜“; 

// 判断两个货物之间关系是否友好 .. 
public static boolean isFriendly(Goods goods1 Goods goods2){ 
if (goods1 != null){ 
if (goods1.getGoodsName().trim().equals(sheepName)){ 
if (goods2 == null){ 
return true;

else{ 
return false; 


else if (goods1.getGoodsName().trim().equals(wolfName)){ 
if (goods2 == null || goods2.getGoodsName().trim().equals(cabbageName)){ 
return true; 

else{ 
return false; 


else if(goods1.getGoodsName().trim().equals(cabbageName)){ 
if (goods2 == null || goods2.getGoodsName().trim().equals(wolfName)){ 
return true; 
}
    else{ 
return false; 
    } 
}
    else{ 
return false; 


else{ 
return false;




// 我就直接写在主方法里了 
  public static void main(String [] args){ 
boolean isSuccess = false; 
            linkedList beforeCrossing = new linkedList(); 
linkedList afterCrossing = new linkedList(); 
beforeCrossing.add(new Goods(sheepName)); 
beforeCrossing.add(new Goods(cabbageName)); 
beforeCrossing.add(new Goods(wolfName)); 
while (!isSuccess) { 
Goods goods1 = beforeCrossing.getFirst(); 
System.out.println(goods1.getGoodsName() + “被取走了“); 
beforeCrossing.removeFirst(); 
if (beforeCrossing.isEmpty()) { 
afterCrossing.addLast(goods1); 
isSuccess = true; 
System.out.println(“全部移动完毕!“); 

else { 
Iterator it = beforeCrossing.iterator(); 
Goods[] beforeCro = new Goods[2]; 
for (int i = 0; it.hasNext(); i++){ 
beforeCro[i] = it.next(); 
System.out.println(beforeCro[i].getGoodsName() + “留了下来“); 

if (isFriendly(beforeCro[0] beforeCro[1])){ 
if (afterCrossing.isEmpty()) { 
afterCrossing.addLast(goods1); 
System.out.println(goods1.getGoodsName() + “被成功的放到了对岸“); 
}
else{ 
Goods goods2 = afterCrossing.getFirst(); 
if (isFriendly(goods1 goods2)){ 
afterCrossing.addLast(goods1); 
System.out.println(goods1.getGoodsName() + “被成功的放到了对岸“); 

else{ 
beforeCrossing.addLast(goods2); 
afterCrossing.removeFirst(); 
System.out.println(goods1.getGoodsName() + “与“ + goods2.getGoodsName() + “并不和睦于是把“ + goods2.getGoodsName() + “带了回来并将“ + goods1.getGoodsName() + “留了下来“); 


}
else{ 
beforeCrossing.addLast(goods1); 
System.out.println(“很可惜 留下来的两个东西并不和睦 于是 “ + goods1.getGoodsName() + “ 又被放了回去“); 






 
class Goo

 属性            大小     日期    时间   名称
----------- ---------  ---------- -----  ----

     文件       2307  2010-01-13 19:54  过河问题1\AcrossTheRiver.class

     文件       3400  2010-01-13 16:25  过河问题1\AcrossTheRiver.java

     文件        362  2010-01-13 19:54  过河问题1\Goods.class

     目录          0  2010-01-13 18:56  过河问题1

----------- ---------  ---------- -----  ----

                 6069                    4


评论

共有 条评论