2016-05-31 2 views
0

최근에 Java로 코딩을 시작했고 코치가 Mastermind 게임을 다시 만들어야하는 운동을했습니다. 이 게임의 개요를 알려면 : 컴퓨터가 X 임의의 정수로 배열을 만들고 사용자가 X 정수도 입력하면됩니다. 위치 문제. 사용자가 컴퓨터 생성 배열과 동일한 지점에있는 정수를 추측하면 사용자는 "Gold"로 점수를 매 깁니다. 정수가 배열에 있지만 잘못된 지점에 있으면 사용자가 "실버"점수를 얻습니다. 정수가 배열에 전혀 존재하지 않으면 사용자는 "NotFound"점수를 얻습니다. 최종 배열은 배열의 각 위치에 대한 점수를 사용자에게 제공해야합니다 (예 : (Gold, Silver, NotFound)Mastermind 게임에서 Nested Loop가 제대로 작동하지 않습니다.

나는 사용자가 추측 한 점수를 내포하는 중첩 루프를 만들려고했다. 다른 배열 (yourScore [])에서 점수를 캡처합니다. 사용자 추측은 배열 "guessednums []"에 캡처되고 컴퓨터 생성 배열은 "nums []"라고합니다. 모든 배열의 크기는 언급 된 코드 이전에 변수로 설정되었습니다.

내가 원하는 것은 사용자의 추측이 동일한 지점에서 컴퓨터 선택과 일치하는지 확인한 다음 yourScore 배열의 일치하는 공간을 "금"으로 설정하는 것입니다. 그런 다음 추측이 직접적으로 일치하지 않으면 사용자가 추측 한 값이 컴퓨터 nums [] 배열의 모든 위치에 있는지 여부를 확인하고이 경우 Silver로 점수를 매기를 원합니다. 마지막으로, 그렇지 않은 경우 yourScore [] 장소를 "NotFound"로 설정해야합니다.

일치하는 추측은 적절하게 "금"으로 채점됩니다. 내가 겪고있는 문제는 때로는 루프가 "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; 
     } 
    } 
} 
+0

우리에게 코딩 운동의 이상 상황을 보여주십시오. 왜 전체 파일이 아닌가요? 변수의 정의는 예를 들어. 'guessednums' 외. 배열의 정의 등과 관련해서'size'의 값처럼 흥미 롭습니다. - 아하지만 하나의 힌트가 있습니다 - 나는 대답을 게시 할 것이지만 어쨌든 질문을 업데이트하십시오. 감사. – Dilettant

+0

전체 파일을 추가했습니다!내 질문에 상당히 구체적인 코드를 사용하여 과부하하고 싶지는 않았지만 전체 코드를 사용하는 것이 왜 더 유용할까요? 감사합니다. –

+0

소중한 사람이며 지역 사회에 오신 것을 환영합니다! 결국 우리는 대답이 증명 된 것처럼 필요한 범위에 대해 옳았습니다. 그러나 솔루션을 제공하는 동안 컨텍스트 정보를 계속 제공하겠다는 약속을 보여주었습니다. 감사! – Dilettant

답변

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 가능하고 독자들에게 항상 더 나은 ...

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; 
      } 
     } 
    } 
} 
+0

내 대답보다 명확 해 IMO : 알고리즘과 더 효율적인 루프 경제를 설명하는 좋은 산문 ... 그리고 아마도 들여 쓰기를 적용하면 ... 알았지. 일관된 형식을 적용하기 전에 내가 놓친 중괄호를 추가했다. ;-) – Dilettant

0

우아하지만 간단하지 :

for(int i = 0; i < 5; i++){    
     yourScore[i] = "NotFound";//most likely 
    } 

    for(int i = 0; i < 5; i++){    
     for(int j = 0; j < 5; j++){    
      if(guessednums[i]==nums[j]) { 
       yourScore[i] = "Silver"; //quite likely 
      }  
     }   
    } 

    for(int i = 0; i < 5; i++){        
      if(guessednums[i]==nums[i]) { 
       yourScore[i] = "Gold"; //very unlikely    
     }   
    } 
관련 문제