嵌套循环在Mastermind游戏中无法正常工作

时间:2016-05-31 09:45:42

标签: java arrays loops if-statement for-loop

我最近开始用Java编码,我的教练给了我一个练习,我必须重新创建Mastermind游戏。概述这个游戏:计算机创建一个具有X个随机整数的数组,用户也可以输入X个整数。位置很重要。用户得分" Gold"如果他猜到一个与计算机生成的数组位于同一位置的整数。如果整数存在于数组中,但是在错误的位置,则用户获得" Silver"得分了。如果数组中根本不存在整数,则用户获得" NotFound"得分了。最终的数组应该为用户提供数组中每个位置的分数,例如(金,银,未发现)

我试图制作一个用户猜测的嵌套循环。它以不同的数组(yourScore [])捕获得分。用户猜测被捕获在数组" guessednums []"并且计算机生成的数组被称为" nums []"。所有数组的大小都是在上述代码之前使用变量设置的。

我想要的代码是首先检查用户的猜测是否与同一地点的计算机选择匹配,如果是这种情况,请将yourScore数组中的匹配空间设置为&#34 ;金&#34 ;.然后,如果猜测没有直接匹配,我想要一个循环来检查用户猜测是否存在于计算机生成的nums []数组的任何位置,并将其评分为" Silver"如果是这样的话。最后,如果不是这种情况,我希望将yourScore []地点设置为" NotFound"。

匹配猜测被正确评分为" Gold"。我遇到的问题是,有时循环不能正确地猜测" Silver",而是将其标记为" NotFound"。我怀疑这与循环没有正确初始化有关。我已经阅读了有关Stack Overflow和其他文章的多个问题,并且使用了我的代码,但我仍然遇到类似的问题。

我希望得到关于代码的第二意见,看看我做错了什么。

package Mastermind;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner; 

public class Mastermind {
    static Scanner userInput = new Scanner(System.in);

    public static void main(String[] args){

        int size = 3; // Allows you to set the size of the arrays in the game

        int[] nums = generateNumbers(size); //Stores the computer choice 3-tuple 
        int[] guessednums; //Stores the guessed 3-tuple
        int iteration = 0; //Keeps track of the # of guesses so far
        boolean correctAnswer; //true if the guessed tuple matches the computer choice tuple

        //Set array size


        //The game starts here
        while (true){
            iteration++;
            System.out.println("Iteration #" + iteration);
            guessednums = guessTheNumbers(size);
            correctAnswer = yourScore(nums, guessednums, size);
            if(correctAnswer) break;
        }

        //Printing the result
        printResults(iteration, nums);

    }

    private static void printResults(int iteration, int[] nums) {
        System.out.println("************************************************************"); // Print final result if users has a completely matching guess
        System.out.println("************************************************************");
        System.out.println("The correct answer was " + Arrays.toString(nums));
        System.out.println("It took you " + iteration + " iterations to find the answer!");
    }

    private static int[] guessTheNumbers(int size) {
        System.out.println("Please your ordered guess (press enter after each):");
        int[] guessednums = new int[size]; // Initialise array for user choices

        for (int i = 0; i < size; i++){ // Loop that creates the array of user input
            guessednums[i] = userInput.nextInt();
        }

        System.out.println(Arrays.toString(guessednums));
        return guessednums; // Return array for user guessed numbers array to main method
    }

    public static int[] generateNumbers(int size){
        int[] nums = new int[size]; // Initialise array for computer choices
        Random rn = new Random(); // Create new variable for randomised computer choices

        for (int i = 0; i < size; i++){ // Loop that creates the array of computer choices
            nums[i] = rn.nextInt(9) + 1;
        }

        System.out.println(Arrays.toString(nums)); // Temporary to print array
        return nums; // Return array for computer generated numbers array to main method

    }

    public static boolean yourScore(int[] nums, int[] guessednums, int size){   
        String[] yourScore = new String[size]; // Initialise array for user choices

        for(int i = 0; i < size;  i++){ // Nested loop that scores the user entries as Gold/Silver/NotFound
            if (guessednums[i] == nums[i]){
                yourScore[i] = "Gold";
            } else {
                yourScore[i] = "NotFound";// in case is not found it stays that way
                for(int j = 0; j < size;  j++){
                    if (guessednums[i] == nums[j]){
                        yourScore[i] = "Silver"; // found one! break the loop and keep checking numbers
                        break;
                    } 
                }
            }
        }


        if (yourScore[0] == "Gold" && yourScore[1] == "Gold" && yourScore[2] == "Gold"){ // Marks the input as true or false depending on if it matches with the computer choices
            boolean correctanswer = true;
            return correctanswer;
        } else {        
            System.out.println("Your score is " + Arrays.toString(yourScore) + "!");
            System.out.println("************************************************************");
            boolean correctanswer = false;
            return correctanswer;
        }
    }
}

3 个答案:

答案 0 :(得分:1)

问题在于逻辑。我觉得将逻辑化为单词很有用:

对于数组中的每个数字: 1.检查该位置的数字是否相等(黄金) 2否则,对于数组中的每个数字,检查该数字是否等于数组中的另一个数字 3.如果该数字在其中,则打破循环(银色) 4.否则,将其标记为未找到(NotFound)。

代码就像这样:

for(int i = 0; i < size;  i++){ // Nested loop that scores the user entries as Gold/Silver/NotFound
    if (guessednums[i] == nums[i]){
        yourScore[i] = "Gold";
    } else {
        yourScore[i] = "NotFound";// in case is not found it stays that way
        for(int j=0;j<size<j++){
            if (guessednums[i] == nums[j]){
                yourScore[i] = "Silver"; // found one! break the loop and keep checking numbers
                break;
            } 
        }
    }
}

答案 1 :(得分:0)

我认为你混淆了外部和内部指数的含义。试试这个:

for(int i = 0; i < size;  i++){ // Nested loop that scores the user entries as Gold/Silver/NotFound
    for(int j = 0; j < size; j++){
        if(i == j) {
            if (guessednums[i] == nums[j]){
                yourScore[i] = "Gold";
            }
        } else {
            if (guessednums[i] == nums[j]){
                yourScore[i] = "Silver";
            } else if (guessednums[i] != nums[j]){
                yourScore[i] = "NotFound";
            } 
        }
    }
}

只有i == j才能获得金奖...... HTH对读者来说总是更好,如果缩进是合理的,因此对眼睛来说很容易......

答案 2 :(得分:0)

不优雅而且简单:

config.py