我正在进行猜谜游戏任务。计算机从R / B / G / Y随机化3个字母,用户试图猜测组合的正确顺序和位置。计数器递增以给出提示,即。计算用户在每次猜测时正确的字母和/或位置,直到缩小范围为止。
这是随机化计算机组合的方法:
public static void newGame(){
// Randomize colour choice (# between 1 and 4)
col1 = (int)(Math.random()*4)+1;
col2 = (int)(Math.random()*4)+1;
col3 = (int)(Math.random()*4)+1;
switch ((int)col1){
case 1: ans1 = ("R");
break;
case 2: ans1 = ("G");
break;
case 3: ans1 = ("B");
break;
case 4: ans1 = ("Y");
break;
}
switch ((int)col2){
case 1: ans2 = ("R");
break;
case 2: ans2 = ("G");
break;
case 3: ans2 = ("B");
break;
case 4: ans2 = ("Y");
break;
}
switch ((int)col3){
case 1: ans3 = ("R");
break;
case 2: ans3 = ("G");
break;
case 3: ans3 = ("B");
break;
case 4: ans3 = ("Y");
break;
}
colchoice = ans1 + " " + ans2 + " " + ans3;
}//end newGame method
这些是我的反方法:
public static void checkColoursCorrect(){
inputnumber(guess1,guess2,guess3);
// Determine how many user inputted letters equal the randomized ones
correctc = 0;
if (uguess1 == col1 || uguess1 == col2 || uguess1 == col3){
correctc++;
}
if (uguess2 == col1 || uguess2 == col2 || uguess2 == col3){
correctc++;
}
if (uguess3 == col1 || uguess3 == col2 || uguess3 == col3){
correctc++;
}
}//end checkColoursCorrect method
public static void checkPositionsCorrect(){
inputnumber(guess1,guess2,guess3);
correctp = 0;
if (uguess1 == col1){
correctp++;
}
if (uguess2 == col2){
correctp++;
}
if (uguess3 == col3){
correctp++;
}
if (uguess1 == col1 && uguess2 == col2 && uguess3 == col3){
System.out.println("User wins! Colour was " + colchoice);
}
}//end checkPositionsCorrect method
我认为,既然组合是随机的,每次计数器方法调用col1 / col2 / col3时,都会使用一个新的组合而不是首先初始化的组合?如果有人能指出我如何解决这个问题,我们将不胜感激。
输入数字方法:
public static void inputnumber(String guess1, String guess2, String guess3){
// Convert user's FIRST guess to a number
if ("R".equals(guess1)){
uguess1 = 1;
}
if ("G".equals(guess1)){
uguess1 = 2;
}
if ("B".equals(guess1)){
uguess1 = 3;
}
if ("Y".equals(guess1)){
uguess1 = 4;
}
// Convert user's SECOND guess to a number
if ("R".equals(guess2)){
uguess2 = 1;
}
if ("G".equals(guess2)){
uguess2 = 2;
}
if ("B".equals(guess2)){
uguess2 = 3;
}
if ("Y".equals(guess2)){
uguess2 = 4;
}
// Convert user's FINAL guess to a number
if ("R".equals(guess3)){
uguess3 = 1;
}
if ("G".equals(guess3)){
uguess3 = 2;
}
if ("B".equals(guess3)){
uguess3 = 3;
}
if ("Y".equals(guess3)){
uguess3 = 4;
}
}
答案 0 :(得分:0)
据我了解,在代码的第一行中,您希望获得col1,col2和col3的随机值。 我认为Java可能与C具有相同的态度,因此您需要在代码中创建一个随机数生成器,以便在每次运行程序时获得新的随机数。否则,在编译时,您只会获得一次随机数。 在此link,您可以看到Oracle的Random类文档。您可能需要创建一个生成器(使用新的Random()),然后使用newInt()在代码中稍后获取随机int值。
当您注意到并发修改时,确保您不从不同方法访问相同的字段是第一个要检查的。