簡體   English   中英

當字符位於數組的第二行時,為什么我的代碼不起作用?

[英]Why does my code not work when a character is in the second row of the array?

我有一些帶有方法的代碼,該方法試圖返回二維數組位置的相反字符標簽。

讓我們假設數組及其每個位置的標簽如下:

{{3,3,3,3}, {3,3,3,3}}
  a,b,c,d    e,f,g,h

如果輸入 b,則返回 f。 如果輸入 a、b、c 或 d,我可以正常工作,但如果輸入 e、f、g 或 h,我就無法正常工作,我不知道為什么。

public class ByteTest {

    public static void main(String[] args) {
        int[][] testArray = {{3,3,3,3}, {3,3,3,3}};
        //                    a b c d    e f g h
        char slectdPit = 'e';
        int total = (int)slectdPit;
        int total97 = total - 97;
        System.out.println(myGetOpposingPit(slectdPit, testArray));
    }

    public static char myGetOpposingPit(char b, int[][] ints) {
        char retChar = 'z';
        int retVal = 0;
        int charPosi = 0;
        int total97 = 0;
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < ints[0].length; j++) {
                charPosi = (int)b;
                total97 = charPosi - 97;
                if (total97 <= ints[0].length) {
                    if (total97 == j) {
                        retVal = (charPosi + ints[0].length);
                        retChar = (char)retVal;
                    }
                }

                else if (total97 > ints[0].length) {
                    if (total97 == (j + (ints[0].length))) {
                        retVal = (charPosi - ints[0].length);
                        retChar = (char)retVal;
                    }
                }
            }
        }
        return retChar;
    }

}

我做了一個 if 語句

 else if (total97 > ints[0].length) {
                if (total97 == (j + (ints[0].length))) {
                    retVal = (charPosi - ints[0].length);
                    retChar = (char)retVal;
                }

這應該找到數組第二行中的標簽,並用characterPosition - 數組行長度分配返回的myGetOpposingPit ,所以如果通過myGetOpposingPit的字符是 g,它會是charPosi (103) minus ints[0].length (4), equaling 99 ,將ascii轉換為 'c'。

但是不起作用, z被返回。 所以我的 if 語句之一沒有運行或什么的。

total97 == ints[0].length時,您的邏輯似乎不正確。 我更改了當它們相等時執行的分支:

public static char myGetOpposingPit(char b, int[][] ints) {
    char retChar = 'z';
    int retVal = 0;
    int charPosi = 0;
    int total97 = 0;

    charPosi = (int)b;
    total97 = charPosi - 97;

    for (int i = 0; i < 2; i++) {

        for (int j = 0; j < ints[0].length; j++) {

            if (total97 < ints[0].length) {
                if (total97 == j) {
                    retVal = (charPosi + ints[0].length);
                    retChar = (char)retVal;
                }
            } else if (total97 >= ints[0].length) {
                if (total97 == (j + (ints[0].length))) {
                    retVal = (charPosi - ints[0].length);
                    retChar = (char)retVal;
                }
            }
        }
    }

    return retChar;
}

我還將total97分配移出循環。 它不會改變,所以不需要每次迭代都計算。

暫無
暫無

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

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