【发布时间】:2018-05-23 17:58:20
【问题描述】:
我目前正在从事一个项目,在该项目中遇到了检测 char 数组中的空索引的问题。问题是它没有检测到数组中是否有空索引。我尝试检测人们所说的不同内容,其中空字符的占位符但它们似乎都不起作用。
以下是我尝试过的不同方法: 0、'0'、'u0000'、'\u0000\ 和 null。
public class TestArrayChecker {
public static void main(String[] args) {
char array1[] = new char[] {'F', 'P', 'S', 'R'};
char array2[] = new char[] {'S', 'P', 'O', 'R'};
char c1 = '\u0000';
char arrayOfCorrect[] = new char[array1.length];
int correct = 0;
int counter = 0;
int close = 0;
int index = 0;
for (int i = 0; i < 4; i++) {
if (getColorAt(i, array1) == getColorAt(i, array2)) {
correct++;
arrayOfCorrect[index] = getColorAt(i, array1);
index++;
}
}
for (int i = 0; i < 4; i++) {
for (int n = -i; n < 4 - i; n++) {
if(getColorAt(i, array1) == getColorAt(i + n, array2)) {
for (int f = 0; f < arrayOfCorrect.length; f++) {
System.out.println(getColorAt(f, arrayOfCorrect) + " " + f);
System.out.println(arrayOfCorrect.length);
System.out.println(getColorAt(f, arrayOfCorrect) != c1);
if (getColorAt(f, arrayOfCorrect) != c1) {
System.out.println(getColorAt(f, arrayOfCorrect) + " " + f);
System.out.println("No Void in this array");
if(getColorAt(i, array1) != getColorAt(f, arrayOfCorrect)) {
System.out.println("This number is close: " + getColorAt(f, arrayOfCorrect));
counter++;
break;
}
} else {
counter++;
System.out.println("We got here!");
}
if (counter == 4) {
close++;
}
}
}
}
}
System.out.println(arrayOfCorrect[0] + " " + arrayOfCorrect[1] + " " + arrayOfCorrect[2] + " " + arrayOfCorrect[3]);
System.out.println(correct);
System.out.println(close);
System.out.println(counter);
}
public static char getColorAt(int index, char array[]) {
// TODO: Fill-in code to return the color at a particular position
return array[index];
}
}
这是代码的主要部分不起作用:
if (getColorAt(f, arrayOfCorrect) != c1) {
System.out.println(getColorAt(f, arrayOfCorrect) + " " + f);
System.out.println("No Void in this array");
if(getColorAt(i, array1) != getColorAt(f, arrayOfCorrect)) {
System.out.println("This number is close: " + getColorAt(f, arrayOfCorrect));
counter++;
break;
}
} else {
counter++;
System.out.println("We got here!");
}
这是控制台的输出,最后两个数字应该打印出1和4。
P 0
4
true
P 0
No Void in this array
R 1
4
true
R 1
No Void in this array
This number is close: R
P 0
4
true
P 0
No Void in this array
This number is close: P
P 0
4
true
P 0
No Void in this array
This number is close: P
P R
2
0
3
我还没有删除我所有的调试代码,所以请忽略它。 谢谢大家的帮助。
【问题讨论】:
-
“问题”是什么意思?你有错误吗?不是想要的输出? (如果是,请edit您的问题并包括错误/所需和当前输出)
-
arrayOfCorrect是否应该将匹配的字母保持在它们在原始数组中的位置? (即[blank, 'P', blank, 'R']) -
arrayOfCorrect 应该只保存已经使用的字母。 (即['P','R',空白,空白])。我知道我使用的索引变量只有在创建数组后才会增加,但我认为这不是导致问题的原因。
-
counter变量计数是什么? -
计数器变量正在计数,以查看当前正在查看的字符是否包含在 arrayOfCorrect 中,抱歉我的变量名称不好,最后我把东西放在一起了。