
以上代码的执行结果是“数组已满”,求勘误、指点!
以上图片中的代码如下:
public class SuppleMent {
public static void main(String[]args){
int index=-1; // 假设的数组下标索引
String[]phones={"小米","中兴","华为",null};
for(int i=0;i
index=i;
break;
}
if(index!=-1){
phones[index]="联想";
for(int j = 0;j
}
}
else {
System.out.println("数组已满!");
}
}
}
}
程序的执行没有问题,确实是三个数组已满。
你的想法应该是一旦在数组中找到空元素就加入新元素,应该在if判断当前元素为空时加入元素。可以在最后输出数组查看。index可以作为判断标准,在循环结坦派携束时index还是-1,说明数组是满的。
public class SuppleMent {
public static void main(String[]args){
int index=-1; // 假设的数组下标索引
String[] phones={"小米","中兴","华为",null};
for(int i=0;i if(phones[i]==null){
index=i;
phones[i]="联想";
}
让伏 }
if(index==-1)
羡困 System.out.println("数组是满的。");
for(int j = 0;j System.out.println(phones[j]);
}
}
}
第二个if语句改为else if
public class SuppleMent {
public static void main(String[] args) {
int index = -1; // 假设的数组下标索引
String[] phones = { "小米", "中兴", "华为", null };
for (int i = 0; i < phones.length; i++) {
if (phones[i] == null) {
index = i;
/*
* 此处如果用break,当数组有空位时就跳出循环了轿伍仔,
* 永远都走不到 phones[index] = "联想"; 这句话。
*/
//break;
}else{
//判断标志位index是否等于-1,是否已循环橘陆到数组的最后一个元素
if(index == -1 && i == phones.length - 1){
System.out.println("数组已满!");
}
}
if (index != -1) {
phones[index] = "联想";
for (int j = 0; j 闭汪< phones.length; j++) {
System.out.println(phones[j]);
}
}
}
}
}