[英]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.