永发信息网

Java题,每题20分

答案:3  悬赏:40  手机版
解决时间 2021-12-03 02:13
  • 提问者网友:我们很暧昧
  • 2021-12-02 05:11
Java题,每题20分
最佳答案
  • 五星知识达人网友:独钓一江月
  • 2021-12-02 06:19
Java代码如下,
可以直接运行的哈~

import java.util.Iterator;
import java.util.LinkedList;

public class AcrossTheRiver {
// 定义三个String对象
public static final String rabbitName = "Rabbit";
public static final String wolfName = "Wolf";
public static final String cabbageName = "Cabbage";

// 判断两个货物之间关系是否友好 写的麻烦了一点= =..
public static boolean isFriendly(Goods goods1, Goods goods2) {
if (goods1 != null) {
if (goods1.getGoodsName().trim().equals(rabbitName)) {
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 true;
}
}

// 我就直接写在主方法里了
public static void main(String[] args) {
boolean isSuccess = false;
LinkedList beforeCrossing = new LinkedList();
LinkedList afterCrossing = new LinkedList();
beforeCrossing.add(new Goods(rabbitName));
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 Goods {
// 货物名称
private String goodsName;

// 默认构造方法
public Goods(String goodsName) {
this.goodsName = goodsName;
}

// 获得货物名称
public String getGoodsName() {
return goodsName;
}

}
全部回答
  • 1楼网友:春色三分
  • 2021-12-02 08:24
买瓶安眠药给猫吃,然后把狗带过去,在河对岸吃狗肉火锅,在把鱼带过来,一起炖了。吃完早过去带猫,结果猫不见了(注意:一定要给猫吃两颗安眠药,不然没得猫肉吃了)
  • 2楼网友:長槍戰八方
  • 2021-12-02 07:36
先带猫过河,空船反回带狗过河,然后再载猫回去,放下猫带鱼过河,空船反回带猫过河
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯