2016-12-01 3 views
0
Уменьшает

Я написал программу, которая принимает Четыре в ряд: входJAVA Connect Four Метод Некорректно Row

  1. пользователя как INT (в качестве переменной выбора)
  2. счетчика INT (автоматически вычисленной переменной из метода, который возвращает символ для R или Y, чтобы вставить в многомерном массиве)

Я тогда написал метод, называемый dropChip, который принимает выбор и подсчет значений следующим образом:

public static void dropChip(int selection, int count) 
{ 
    --selection;//make selection a human number 
    if (grid[r][selection] == ' ')//while r(row) & selection is empty char 
    { 
    grid[r][selection] = userChip(count);//drop R or Y into grid 
    } 
    else if (grid[r][selection] != ' ')//while r selection has a letter value 
    { 
    int x = r--;//set x to value of decremented r 
    grid[x][selection] = userChip(count);//drop chip in next row of same column 
    } 
} 

Вот пример моего выхода в терминале:

| | | | | | | 
| | | | | | | 
| | | | | | | 
| | | | |R| | 
| | | |Y| | | 
| | |R| | | | 

Yellow player's turn. 
Input a value between 1 and 6 to drop your chip: 3 

| | | | | | | 
| | | | | | | 
| | |Y| | | | 
| | | | |R| | 
| | | |Y| | | 
| | |R| | | | 

Вопрос: Почему Y- и R в колонке 2 (3 человека в) не укладываются друг на друга непосредственно? Значение r должно быть локальным для вызова метода, а не глобальным, а? Что дает?

Добавление полную программу здесь, в случае, если кто хочет смотреть глубже:

import java.util.*; 
//create connectFour class 
public class connectFour 
{ //main method and public declarations 
    public static Scanner input = new Scanner(System.in); 
    public static int selection = 0; 
    //create variable for square multidimensional array usage 
    public static int y = 6; 
    //build new two dimensional array of 3 rows with 3 columns 
    public static char[][] grid = new char[y][y]; 
    public static int r = grid.length - 1;//6 as human number 
    public static int c = grid[r].length - 1;//6 as human number 

    public static void main(String[] args) 
    { 
     System.out.println(); 
     System.out.println("===============START PROGRAM===============\n"); 
     //create game prompt 
     String prompt = "Welcome to the classic Connect Four game!\n\nThis program will start with the red player\nthen move to the yellow player.\n\nYou will chose a numerical value\nbetween 1 and 6 as the column to drop your chip.\n\nOnce you have dropped your chip, the program will scan\nthe columns and rows looking for a win.\nYou can win by having four chips stacked either\nhorizontally, vertically or diagonally.\n\nGood Luck!\n"; 
     System.out.print(prompt); 

     //call the loadBlanks method with the variable of grid 
     loadBlanks(grid); 
     controller(); 
     //check4Win(grid, selection); 
     System.out.println("===============END PROGRAM==============="); 
    } 

    public static void controller() 
    { 
     //set maximum number of user attempts (36 in this case) 
     int maxAttempts = r * c; 
     //create an empty int 
     int count = 0; 
     //while the count value is less than maxAttempts 
     while (count < maxAttempts) 
     { 
     //determine which user turn it is sending count number 
      userTurn(count); 
      //print prompt for user disc 
      System.out.print("Input a value between 1 and 6 to drop your chip: "); 
      //store user value in selection 
      selection = input.nextInt(); 
      System.out.println(); 
      //send human number of selection to method that drops chip along with count value 
      dropChip(selection, count); 
      //print the connect four game 
      printValues(grid); 
      //increment value of count 
      count++; 
     } 
    } 

    public static void loadBlanks(char[][] grid) 
    {//while row is < total count of rows 
     for (int row = 0; row < grid.length; row++) 
     {//while column in row is < total count of columns 
      for (int column = 0; column < grid[row].length; column++) 
      {//fill grid with blank values 
       grid[row][column] = ' '; 
      }//end inner loop 
     }//end outer loop 
    } 

    public static void dropChip(int selection, int count) 
    { 
     --selection;//make selection a human number 
     int x = grid.length - 1; 
     if (grid[x][selection] == ' ') 
     { 
      grid[x][selection] = userChip(count); 
     } 

     else if (grid[x][selection] == 'R' || grid[x][selection] == 'Y')//(grid[x][selection] == 'R' || grid[r][selection] == 'Y') 
     { 
      grid[x-1][selection] = userChip(count); 
     } 
    } 

    //print all of the values in the array 
    public static void printValues(char[][] grid) 
    {//while row is < total count of rows 
     for (int row = 0; row < grid.length; row++) 
     {//while column in row is < total count of columns 
      for (int col = 0; col < grid[row].length; col++) 
      {//print inner loop bracket 
       System.out.print("|" + grid[row][col]); 
      }//end inner loop 
     System.out.println("|");//print outer loop bracket 
     }//end outer loop 
    } 

    //return the value of the user chip based on turn as char 
    public static char userChip(int count) 
    { 
     //set userColor to random value 
     char userColor = ' '; 

     //if the passed value of int x is evenly divisibly by 2, set char to R 
     if (count % 2 == 0) 
     { 
      userColor = 'R'; 
     }//end if 
     //else if the int of x modulo 2 != 0, set char to Y 
     else if (count % 2 != 0) 
     { 
      userColor = 'Y'; 
     }//end elseif 
     return userColor;//set value of char to userColor 
    } 

    //calculate user turn based on count value starting with red 
    public static void userTurn(int count) 
    { 
     String color = " "; 
     if (count % 2 == 0) 
     { 
      color = "Red"; 
     }//end if 
     //else if the int of x modulo 2 != 0, set char to Y 
     else if (count % 2 != 0) 
     { 
      color = "Yellow"; 
     }//end elseif 
     System.out.println();//whitespace for terminal 
     System.out.println(color + " player\'s turn.");//print user turn 
    } 
+0

Во-первых, ваш 'else' условиями не требует вложенным' if' – nullpointer

+0

..'r' не объявлен локально сохранить свое значение связано ... и его не знали, что 'userChip() 'делает – nullpointer

+0

Спасибо @nullpointer. Я добавил полную программу в нижней части моего оригинального сообщения. Обратите внимание, что я изменил dropChip(), чтобы попытаться включить локальную переменную для grid.length-1 (ранее глобально доступная переменная r). Любое понимание очень ценится. – Fergus

ответ

0

Я нашел ответ вчера вечером. Используя глобальное значение r, мой код уменьшал это значение глобально в любое время, когда значение -r было эквивалентно значению R или Y. Чтобы решить эту проблему, я использовал локальный цикл for с x, где x = grid.length-1, и уменьшил это значение при каждом прохождении метода. Ниже приведен мой рабочий пример метода dropChip. Я ценю комментарии и помощь каждого!

public static void dropChip(int selection, int count) 
{ 
    --selection;//make selection a human number 
    for (int x = grid.length-1; x >= 0; --x)//set x to value of decremented r 
    { 
     if (grid[x][selection] == ' ')//while r(row) & selection is empty char 
      { 
       grid[x][selection] = userChip(count);//drop R or Y into grid 
       break; 
      } 
      //else grid[x][selection] = userChip(count);//drop chip in next row of same column 
    } 

} 
0

Хорошо отладки кода буквально. Я получаю, чтобы увидеть это в вашем объявлении static void dropChip(int selection, int count) метод -

else if (grid[x][selection] == 'R' || grid[x][selection] == 'Y') { 
      grid[x - 1][selection] = userChip(count); 
     } 

это то, что позволяет избежать дублирования. Поскольку, если вы находите 'R' или 'Y' в текущем блоке, вы помещаете новый символ в строку сетки x-1 в том же столбце (чуть выше).

В случае, если вы просто хотите, чтобы перезаписать существующие значения в текущем блоке вы можете изменить метод dropChip к -

public static void dropChip(int selection, int count) { 
    --selection; 
    int x = grid.length - 1; 
    grid[x][selection] = userChip(count); 
} 

Кроме того, если вы вместо того, чтобы использовать

int x = r--; 

то время количество строк, каждый раз при достижении этого сокращения инструкции на 1. Результат в восходящем блоке, заполняющем ваш образец вывода, разделяемый в вопросе.


Редактировать - На стороне записки, так как вы принимаете только один вход в ваш controller я не вижу, как вы хотите, чтобы заполнить строки над второй последней в текущей логике (или последний в обновленной логики.)

Предложение - Попробуйте и принять вклад в виде строк и столбцов, чтобы заполнить точный блок с требуемым характером.

+1

Большое спасибо за ваш ответ @nullpointer! Я попробовал обновить свой код с помощью цикла for, чтобы уменьшить локальное значение для r вместо использования глобальной переменной, и это сработало. – Fergus

Смежные вопросы