请用JAVA编写牧师和野人过河问题成完整程序
时间: 2023-08-09 19:07:23 浏览: 242
以下是一个简单的 Java 程序,实现了牧师和野人过河问题的解决方案:
```
import java.util.Scanner;
public class Main {
static int m, n; // m: 牧师数量, n: 野人数量
static int boatCapacity = 2; // 船的容量
static int[] left = new int[]{m, n}; // 左岸牧师和野人数量
static int[] right = new int[]{0, 0}; // 右岸牧师和野人数量
static boolean boatOnLeft = true; // 船是否在左岸
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入牧师数量:");
m = scanner.nextInt();
System.out.print("请输入野人数量:");
n = scanner.nextInt();
while (true) {
printStatus();
if (right[0] == m && right[1] == n) {
System.out.println("恭喜你,游戏胜利!");
break;
}
if (boatOnLeft) {
System.out.print("请输入要带几个牧师过河(最多 " + Math.min(left[0], boatCapacity) + " 个):");
int p = scanner.nextInt();
System.out.print("请输入要带几个野人过河(最多 " + Math.min(left[1], boatCapacity) + " 个):");
int c = scanner.nextInt();
if (p + c > boatCapacity) {
System.out.println("船的容量不够!");
continue;
}
if (left[0] < p || left[1] < c) {
System.out.println("左岸没有足够的牧师或野人!");
continue;
}
left[0] -= p;
left[1] -= c;
right[0] += p;
right[1] += c;
boatOnLeft = false;
} else {
System.out.print("请输入要带几个牧师过河(最多 " + Math.min(right[0], boatCapacity) + " 个):");
int p = scanner.nextInt();
System.out.print("请输入要带几个野人过河(最多 " + Math.min(right[1], boatCapacity) + " 个):");
int c = scanner.nextInt();
if (p + c > boatCapacity) {
System.out.println("船的容量不够!");
continue;
}
if (right[0] < p || right[1] < c) {
System.out.println("右岸没有足够的牧师或野人!");
continue;
}
left[0] += p;
left[1] += c;
right[0] -= p;
right[1] -= c;
boatOnLeft = true;
}
if ((left[1] > left[0] && left[0] > 0) || (right[1] > right[0] && right[0] > 0)) {
System.out.println("游戏失败!");
break;
}
}
scanner.close();
}
static void printStatus() {
System.out.println("左岸:" + left[0] + " 个牧师," + left[1] + " 个野人");
System.out.println("右岸:" + right[0] + " 个牧师," + right[1] + " 个野人");
System.out.println("船在" + (boatOnLeft ? "左岸" : "右岸"));
System.out.println("--------------------");
}
}
```
程序中,我们使用了一个长度为 2 的整型数组 left 和 right 分别表示左岸和右岸的牧师和野人数量,以及一个布尔变量 boatOnLeft 表示船是否在左岸。程序通过不断循环,接受用户输入,移动船只,并判断游戏是否胜利或失败。
阅读全文