簡體   English   中英

C# 返回錯誤的整數值

[英]C# Returning Wrong Integer Value

我正在嘗試根據用戶的輸入返回一個索引,輸入只有 2 個字符,例如 a1、b2、c3 ......

public int returnInt(string x)
        {
            if (x == "a")
                return 0;
            else if (x == "b")
                return 1;
            else if (x == "c")
                return 2;
            else if (x == "d")
                return 3;
            else if (x == "e")
                return 4;
            else if (x == "f")
                return 5;
            else if (x == "g")
                return 6;
            else if (x == "h")
                return 7;
            else if (x == "1")
                return 0;
            else if (x == "2")
                return 1;
            else if (x == "3")
                return 2;
            else if (x == "4")
                return 3;
            else if (x == "5")
                return 4;
            else if (x == "6")
                return 5;
            else if (x == "7")
                return 6;
            else if (x == "8")
                return 7;
            return 0;
        }

這就是我使用該方法的地方:

var toMove = myButtonArray[returnInt(totxt.Text.Substring(0)), returnInt(totxt.Text.Substring(1))];

該方法適用於第二個子字符串,但不適用於第一個子字符串(0)。 誰能幫我解決這個問題? 當我輸入 a1 時,程序應該返回 1 和 1,但它只為第一個子字符串返回 0。

讓我們使用單個字符,而不是字符串s:

public int returnInt(char x) =>
    x >= 'a' && x <= 'h' ? x - 'a'
  : x >= '1' && x <= '8' ? x - '1'
  : 0;

然后你可以放:

var toMove = myButtonArray[returnInt(totxt.Text[0]), returnInt(totxt.Text[1])];

請注意,我們得到0th1st char ,而不是string

由於您的輸入字符串始終只有 2 個字符,並且您想將它們用作二維數組的索引,因此您需要將代碼更改為以下內容:

var toMove = myButtonArray[returnInt(totxt.Text.Substring(0,1)), 
                           returnInt(totxt.Text.Substring(1,1))];

這樣,您對 String.Substring 函數說一次返回 1 個字符,並將起始索引作為第一個輸入參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM