我想检查一个Array元素是否为空。
我初始化了一个大小为2的String
数组。我循环遍历数组并检查数组元素是否为null。如果它为空,我将添加String
" a"只到那个位置。
下面的代码将产生以下输出:
1=a
2=a
代码:
public class CheckArrayElementIsNull {
public static void main(String[] args) {
String[] arr = new String[2];
for(int i = 0; i < arr.length; i++) {
if(arr[i] == null) {
arr[i] = "a";
}
System.out.println(i + "=" + arr[i]);
if(arr[i] == null) {
System.out.println(i + "= null");
}
}
}
}
我尝试在if条件之后添加一个休息符,但不打印任何内容。
public class CheckArrayElementIsNull {
public static void main(String[] args) {
String[] arr = new String[2];
for(int i = 0; i < arr.length; i++) {
if(arr[i] == null) {
arr[i] = "a";
break;
}
System.out.println(i + "=" + arr[i]);
if(arr[i] == null) {
System.out.println(i + "= null");
}
}
}
}
我期待这个输出:
1=a
2=null
答案 0 :(得分:2)
你的循环中有一些问题。
for(int i = 1; i < arr.length - 1; i++) { //<---- This does not iterate over the entire array, leaving out the first and last elements
if(arr[i] == null) {
arr[i] = "a";
break; //<---- This terminates the loop entirely, if you want to stop all instructions past this one try using continue instead
}
System.out.println(i + "=" + arr[i]);
if(arr[i] == null) { //This code is unreachable as arr[i] is initialized if it was detected as null before
System.out.println(i + "= null");
}else{
System.out.println(i + "=" + arr[i]);
}
}
相反,你应该尝试
for(int i = 0; i < arr.length; i++) {
if(arr[i] == null) {
arr[i] = "a";
System.out.println(i + "= null");
break;
}
System.out.println(i + "=" + arr[i]);
}
答案 1 :(得分:0)
在输入null
循环之前,请尝试在您希望不是for
的索引处指定值:
String[] arr = new String[3];
arr[1] = "a";
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == null)
{
System.out.println(i + "=null");
}
else
{
System.out.println(i + "=" + arr[i]);
}
}
答案 2 :(得分:0)
这是因为break
将打破for
循环的迭代,并立即退出循环。你应该稍微改变你的设计。从我理解你试图实现(分配“a”到遇到的第一个null元素并停止,打印数组中的所有元素)以下应该工作: -
public class CheckArrayElementIsNull {
public static void main(String[] args) {
String[] arr = new String[3];
boolean flag=true; //use a flag that will check if null is encountered
for(int i = 0; i < arr.length; i++) {
if(arr[i] == null && flag) { // first time flag will be true
arr[i] = "a";
flag=false; //set flag to false , to avoid further assignment of 'a' to null values
}
System.out.println(i + "="+ arr[i]); //print array
}
}
}