Табло с отрицательным значением в многомерном массиве с исключением - PullRequest
0 голосов
/ 17 мая 2018

Я застрял.

Я сейчас занимаюсь табло.

У меня проблема с кодом, которая немного раздражает

string[,] table = new string[104, 15];
int xIndex = 0;
int yIndex = 0;
string newPrevious = "placeholder";
//P = BLUE, B = RED, T = GREEN
string[] strData = { "B  ,T  ,P  ,P B,T  ,B  ,B  ,B  ,B  ,T  ,B  ,P  " };

 for (int i = 0; i < strData.Length; i++)
    {
        OriginalData += strData[i];
        OriginalData += ",";
    }
    string[] newNewData = OriginalData.Split(',');
    string result = "";
    string previous = "";
    int counterForTie = 0;
    foreach (string newStrData in newNewData)
    {
        Debug.Log("This is the data : " + newStrData);

        GameObject o = Instantiate(prefab_gameobject) as GameObject;
        o.transform.SetParent(pos_big_road);
        o.transform.localScale = Vector3.one;

        img = (RawImage)o.GetComponent<RawImage>();

        //check the length so that it won't throw an exception
        if (newStrData.Length > 1)
        {
            //get only the first letter of the value P,B,T
            result = newStrData.Substring(0, 1);
        }
        else
        {
            result = "";
        }

        if (table.GetLength(0) < xIndex)
        {
            break;
        }


        if (result.Equals(newPrevious) || result.Equals("T") && yIndex < table.GetLength(1))
        {
            yIndex += 1;
            table[xIndex, yIndex] = result;
        }
        else if (result.Equals(newPrevious) && previous.Equals("T") && yIndex < table.GetLength(1))
        {
            yIndex += 1;
            table[xIndex, yIndex] = result;
        }
        else
        {
            xIndex += 1;
            yIndex = 0;
            table[xIndex, yIndex] = result;
        }
        previous = result;

        if (!result.Equals("T"))
        {
            newPrevious = previous;
        }

        o.transform.localPosition = new Vector3(xIndex * 93, yIndex * -93, 0f);

Теперь этот код будет выглядеть следующим образом

enter image description here

Теперь, если я объявлю свой xIndex = -1;, он будет выглядеть следующим образом

enter image description here

Но настоящая проблема заключается в том, что я начинаю менять свою строкуданные как это

int xIndex = -1;
string[] strData = { "T  ,T  ,P  ,P B,T  ,B  ,B  ,B  ,B  ,T  ,B  ,P  " };

Это дает мне ошибку

IndexOutOfRangeException: индекс массива выходит за пределы диапазона.

Но когда я меняю свой xIndex к этому

int xIndex = 0;

Это даст этот вывод

enter image description here

Какой мой ожидаемый результат должен быть таким

enter image description here

Ответы [ 2 ]

0 голосов
/ 18 мая 2018

15 часов без сна Я придумал это

Я добавил некоторые из этих переменных

string previous = "";
int counterForTie = 0;
int counterForRow = 1;
int justMoveToY = 1;

и полон if и else операторов

if (result.Equals(newPrevious) || result.Equals("T") && yIndex < table.GetLength(1))
        {
            if (counterForRow == 1)
            {
                yIndex = 0;
                counterForTie++;
                table[xIndex, yIndex] = result;
                counterForRow++;
            }
            else { 
                yIndex += 1;
                counterForTie++;
                table[xIndex, yIndex] = result;
            }
        }
        else if (result.Equals(newPrevious) && previous.Equals("T") && yIndex < table.GetLength(1))
        {
            yIndex += 1;
            counterForTie++;
            table[xIndex, yIndex] = result;
        }
        else
        {
            if (justMoveToY == 1 && counterForRow == 1)
            {
                xIndex = 0;
                yIndex = 0;
                table[xIndex, yIndex] = result;
                justMoveToY++;
                counterForRow++;

            }
            else if (justMoveToY == 1)
            {
                xIndex = 0;
                yIndex += 1;
                table[xIndex, yIndex] = result;
                justMoveToY++;
            }
            else
            {
                xIndex += 1;
                yIndex = 0;
                table[xIndex, yIndex] = result;
                counterForTie = 0;
            }
        }

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

if (counterForTie < 6)
{
    o.transform.localPosition = new Vector3(xIndex * 93, yIndex * -93, 0f);
}
else
{
    int reminder = counterForTie % 5;
    o.transform.localPosition = new Vector3((xIndex + reminder) * 93,  -465, 0f);
}

и, наконец, избавьтесь от ExceptionError : Array out of index

int xIndex = 0;

и заставьте его оказаться на первомстрока в первом столбце моей доски

if (counterForRow == 1)
{
    yIndex = 0;
    counterForTie++;
    table[xIndex, yIndex] = result;
    counterForRow++;
 }
 else { 
     yIndex += 1;
     counterForTie++;
     table[xIndex, yIndex] = result;
 }

Хотя у меня все еще есть проблема с этим, но это большой шаг для меня.Спасибо

0 голосов
/ 17 мая 2018

Вы получаете доступ к индексу массива, используя отрицательное целое число, которое просто недопустимо в большинстве языков программирования. Отсюда IndexOutOfRangeException: Array index is out of range" error.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...