背景简介/问题描述
一个房间里,天花板上挂有一串香蕉,有一只猴子可在房间里任意活动(到处走动,推移箱子,攀登箱子等)。设房间里还有一只可被猴子移动的箱子,且猴子登上箱子时才能摘到香蕉,问猴子在某一状态下(设猴子位置为A,香蕉位置在B,箱子位置为C),如何行动可摘取到香蕉。
用java实现猴子摘香蕉
在题目中要求以一维方式实现,但实际上我们可以将三个物体的位置拓展到二维,既将它们的位置设为(x,y)。
monkey类:
public class monkey {
public int x, y;
monkey(){
}
monkey(int x, int y){
this.x = x;
this.y = y;
}
public void monkeymove(int x, int y){
if (this.x == x && this.y == y)
return;
System.out.println("猴子从("+this.x+","+this.y+")移动到了("+x+","+y+")");
this.x = x;
this.y = y;
}
public void movebox(box b, int x, int y){
if (b.x == x && b.y == y)
return;
System.out.println("猴子将箱子从("+this.x+","+this.y+")移动到了("+x+","+y+")");
this.x = x;
this.y = y;
b.setX(x);
b.setY(y);
return;
}
public void climb(){
System.out.println("猴子爬上了箱子");
}
}
banana类:
public class banana {
public int x, y;
banana(){
}
banana(int x, int y){
this.x = x;
this.y = y;
}
}
box类:
public class box {
public int x, y;
box(){
}
box(int x, int y){
this.x = x;
this.y = y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
main函数如下:
import java.util.Scanner;
public class monkeyreachbanana {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("房间大小为16x16");
int x, y;
System.out.println("请输入猴子的位置(x,y)");
x = sc.nextInt();
y = sc.nextInt();
while (x > 16 || x < 0 ||y > 16 || y < 0) {
System.out.println("输入位置有误,请重新输入");
x = sc.nextInt();
y = sc.nextInt();
}
monkey hou = new monkey(x, y);
System.out.println("请输入箱子的位置(x,y)");
x = sc.nextInt();
y = sc.nextInt();
while (x > 16 || x < 0 ||y > 16 || y < 0) {
System.out.println("输入位置有误,请重新输入");
x = sc.nextInt();
y = sc.nextInt();
}
box xiang = new box(x, y);
System.out.println("请输入香蕉的位置(x,y)");
x = sc.nextInt();
y = sc.nextInt();
while (x > 16 || x < 0 ||y > 16 || y < 0) {
System.out.println("输入位置有误,请重新输入");
x = sc.nextInt();
y = sc.nextInt();
}
banana jiao = new banana(x, y);
start(hou, xiang, jiao);
return;
}
private static void start(monkey hou, box xiang, banana jiao) {
while (!reach(hou, xiang, jiao))
{
hou.monkeymove(xiang.x, xiang.y);
hou.movebox(xiang, jiao.x ,jiao.y);
}
hou.climb();
System.out.println("猴子摘到了香蕉");
}
public static boolean reach(monkey hou, box xiang, banana jiao){
if (hou.x == xiang.x && xiang.x == jiao.x
&& hou.y == xiang.y && xiang.y == jiao.y)
return true;
else
return false;
}
}
实验结果
运行结果如图所示: