2017-04-16 50 views
-1

我目前正在從事一個學校項目,其中的任務是使用Arrays和for循環重新創建遊戲「MasterMind」,但是,我很難正確添加白釘的數量,並且我得到這樣的輸出。Master Mind Arrays

4 
7 
2 
1 
What is your guess? No spaces 
4444 
there are 1 reds, and 2 whites 

正如你所看到的,它錯誤地輸出了錯誤數量的白釘。任何建議和/或解決我的問題將不勝感激。

public static void MasterMind(){ 
     Scanner input = new Scanner(System.in); 
     Random r = new Random(); 
     int red = 0, white = 0; 
     int ball; 
     int userInput; 
     int[] ballNum; 
     ballNum = new int[4]; 
     int[] Input; 
     Input = new int[4]; 
     ball = r.nextInt(9999-1000)+1000; 
     for (int i = 0; i < 4; i++){ 
      ballNum[i] = ball%10; 
      ball /= 10; 
      System.out.println(ballNum[i]); 
     } 
     for (int d = 0; d < 8; d++){ 
      System.out.println("What is your guess? No spaces"); 
      userInput = input.nextInt(); 
      for(int i = 0; i < 4; i++){ 
       Input[i] = userInput % 10; 
       userInput /= 10; 
      } 
      for (int i = 0; i < 4; i++){ 
       int m = 0; 
       int n = 0; 
       if(Input[i] == ballNum[i]){ 
        red++; 
        Input[i] = 10000; 
       } 
       m++; 
       n++; 
      } 
      for(int i = 0; i < 4; i++){ 
       for(int j = 0; j < 4; j++){ 
        if(i != j && Input[j] == ballNum[i]){ 
         white++; 
         Input[j] = 1000000; 
        } 
       } 
      } 
      white -= red; 

      if(white < 0){ 
       white = 0; 
      } 
      System.out.println("there are "+red+" reds, and "+white+" whites"); 
      white = 0; 
      red = 0; 
     } 
    } 
+0

你能解釋一下1)正確的輸出應該是什麼,以及2)背後的算法應該是怎樣的邏輯來工作? –

+0

對於我提供的示例,輸出應該爲0,並且我試圖將輸入的數字與每個「球」數字進行比較,當它們匹配時,將輸入的數字重新分配給沒有輸入的數字等於球號 –

+0

的機會如此,4與4444中的前4匹配,並且其他與紅色計數= 1不匹配,並且在最後白色= 0並且減去紅色等於-1,其應該被閾值限制爲0我是對不對? –

回答

0

主要問題是您的循環將用戶輸入轉換爲數組。你做錯了順序。用下面的代碼替換該循環。

for(int i = 3; i >=0; i--){ 
    Input[i] = userInput % 10; 
     userInput /= 10; 
} 

而另一個重要的是你爲什麼從白色減少紅色?只是刪除線

 white -= red; 

那麼你的程序工作正常