如何从输入字段中获取字符串并使用它来计算数组的总和?

时间:2017-11-24 07:48:10

标签: c#

我正在使用Unity3D处理我的应用程序,我正在尝试从输入字段获取用户输入字符串,然后使用该字符串通过应用变量中的值来计算总和,但是无法开始工作。我有这个

int B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U;

int characterLength = 0;
int numberLength = 0;

List<int> fomulaList = new List<int>();
List<int> numberList = new List<int>();

foreach (char c in charactersField.text)
{
    characterLength++;
    fomulaList.Add(c);

    Debug.Log(c);
 }

formulaArray = fomulaList.ToArray();

Debug.Log("Formula Length: " + formulaArray.Length + " " + formulaArray[0].ToString("D1") + " " + formulaArray[1].ToString("D1"));

让我们说:我输入了BC,当我打印出DebugLog时我得到了

公式长度:2 66 67

很好

foreach (char c in numbersField.text)
{
    numberLength++;

    Debug.Log(c);
}

for (int i = 0; i < winningNumberArray.Length; i++)
{
    B = winningNumberArray[i] / 100000;                 //100000
    C = (winningNumberArray[i] % 100000) / 10000;       //10000
    D = (winningNumberArray[i] % 10000) / 1000;         //1000
    E = (winningNumberArray[i] % 1000) / 100;           //100
    F = (winningNumberArray[i] % 100) / 10;             //10
    G = winningNumberArray[i] % 10;                     //1

    H = twoNumberArray[i] / 10;                         //10
    I = twoNumberArray[i] % 10;                         //1

    J = firstThreeNumberArray[i] / 100;                 //100
    K = (firstThreeNumberArray[i] % 100) / 10;          //10
    L = firstThreeNumberArray[i] % 10;                  //1

    M = secondThreeNumberArray[i] / 100;                //100
    N = (secondThreeNumberArray[i] % 100) / 10;         //10
    O = secondThreeNumberArray[i] % 10;                 //1

    P = thirdThreeNumberArray[i] / 100;                 //100
    Q = (thirdThreeNumberArray[i] % 100) / 10;          //10
    R = thirdThreeNumberArray[i] % 10;                  //1

    S = fourthThreeNumberArray[i] / 100;                //100
    T = (fourthThreeNumberArray[i] % 100) / 10;         //10
    U = fourthThreeNumberArray[i] % 10;                 //1

    int sum = formulaArray.Sum();

    Debug.Log("Sum: " + sum.ToString());

但是当我打印出来的时候我得到了

总和:133

在我看来,B和C的值不是来自

B = winnerNumberArray [i] / 100000;
C =(winningNumberArray [i]%100000)/ 10000;

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

问题很可能是您将char 'B'与变量B混淆。尽管有相似之处,但它们完全不相关。

听起来你要做的就是接受用户输入,并根据用户输入获得特定值。通常,在C#中,正确的数据结构是Dictionary

在您的情况下,您需要:

Dictionary<char,int>

其中char是关键字(例如'A''B'),int是您当前添加到A或{{1}的值变量)。