我是一名新程序员,目前正在学习 Java。我在这里有一个基于游戏让我们做个交易和 monty hall 问题 (https://www.youtube.com/watch?v=mhlc7peGlGg) 的游戏,我一直对这段代码的逻辑有疑问。一切似乎都正常,除了我似乎无法让 user_door 切换到另一扇门并正确确定他们是否是赢家。如果有人可以帮助我理解我在这里做错了什么,我很乐意借此机会学习,谢谢!
import java.util.Random;
import java.util.Scanner;
public class GameShow {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
Random generator = new Random();
// Initialize Variables
int user_door,
open_door,
other_door,
prize_door;
// Generate random value 1-3
prize_door = generator.nextInt(3)+1;
open_door = prize_door;
while(open_door == prize_door){
open_door = generator.nextInt(3)+1;
}
other_door = open_door;
while (other_door == open_door || other_door == prize_door){
other_door = generator.nextInt(3)+1;
}
// Begin Game
System.out.println("*** Welcome to the game show! ***");
System.out.println("Select the door (1, 2, or 3): ");
user_door = scan.nextInt();
// User Validation
if (user_door > 3 || user_door < 0) {
System.out.println("Please select door 1, 2, or 3");
user_door = scan.nextInt();
} else if(user_door == 1 || user_door == 2 || user_door == 3) {
//Continue Game
System.out.println("\nIn a moment, I will show you where the prize is located,");
System.out.println("but first I will show you what is behind one of the other doors");
//Continue Dialogue
System.out.println("\nBehind door number " + open_door + " are goats!");
System.out.println("You selected door number " + user_door);
System.out.println("\nWould you like to switch your door(y/n)? ");
//User Input Yes or No
char userReply = scan.next().charAt(0);
//If statement with nested while statements for user input
if (userReply == 'y'){
user_door = other_door;
} while(userReply != 'y' && userReply != 'n')
{
//User Validation
System.out.println("Please enter either y/n");
userReply = scan.next().charAt(0);
}
System.out.println("The prize is behind door number: " + prize_door);
//Check to see if user won or lost
if(user_door == prize_door){
System.out.println("Congratulations! You won the prize!");
} else {
System.out.println("Sorry. You lost.");
}
}
}
}
最佳答案
我同意 Srikanth 上面所说的。缺少的是测试用户回复的部分。你应该切换“if”和“while”语句。这将有助于解决您的门开关问题。
之前
if (userReply == 'y')
{
user_door = other_door;
}
while(userReply != 'y' && userReply != 'n')
{
//User Validation
System.out.println("Please enter either y/n");
userReply = scan.next().charAt(0);
}
改为
while(userReply != 'y' && userReply != 'n')
{
//User Validation
System.out.println("Please enter either y/n");
userReply = scan.next().charAt(0);
}
if (userReply == 'y')
{
user_door = other_door;
}
你这样做的方式只检查第一次输入一个字符。如果他们做错了并试图再做一次,那么它就不会切换门,因为你已经过了程序的那部分。
关于java - 蒙蒂霍尔游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26305386/