【发布时间】:2014-10-10 18:00:45
【问题描述】:
我是一名新程序员,目前正在学习 Java。我在这里有一个基于游戏 Let's make a deal & 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.");
}
}
}
}
【问题讨论】:
-
您是否尝试过附加调试器并逐行逐行执行代码,以查看程序究竟在哪一点偏离了您对它应该做什么的期望?
-
你在使用 Eclipse 吗?
-
我目前正在对您的工作进行代码审查。跟踪问题的时间有点长,所以我会在几分钟内解释一些您可以优化的内容。
-
如果您使用的是 Eclipse,要查看变量,请转到 Window -> Show View -> Variables,或者按 Alt+Shift+Q,V
-
如果您担心班上的其他人共享您的代码,请不要在 Internet 上的公共站点上发布您的代码。在您得到答案后试图编辑所有相关人员的答案以避免其他人学习您所做的相同事情是违反 SO 政策的。除此之外,人们也可以通过查看编辑历史来查看源代码。
标签: java logic probability