请告诉我如何正确使用此中断选项?
它告诉你
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "names[i]" is null
at Main.main(Main.java:23)
TY
public class Main {
public static void main(String[] args) {
String[] names = new String[ 20 ];
names[ 1 ] = "Vasya";
names[ 5 ] = "Vasya5";
names[ 11 ] = "Vasya11";
names[ 13 ] = "Matilda";
names[ 17 ] = "Vasya17";
names[ 18 ] = "Vasya19";
//int total = names.length;
int i = 0;
while (i< names.length) {
if (names[ i ] == null) {
i++;
continue;
}
System.out.println(names[ i ]);
i++;
if (names[i].equals("Matilda"))
break;
}
System.out.println("Finish");
}
}
在 while 循环结束时递增:
public class Main {
public static void main(String[] args) {
String[] names = new String[20];
names[1] = "Vasya";
names[5] = "Vasya5";
names[11] = "Vasya11";
names[13] = "Matilda";
names[17] = "Vasya17";
names[18] = "Vasya19";
int i = 0;
while (i < names.length) {
if (names[i] == null) {
i++;
continue;
}
System.out.println(names[i]);
if (names[i].equals("Matilda"))
break;
i++;
}
System.out.println("Finish");
}
}
或者使用 for 循环代替:
public class Main {
public static void main(String[] args) {
String[] names = new String[20];
names[1] = "Vasya";
names[5] = "Vasya5";
names[11] = "Vasya11";
names[13] = "Matilda";
names[17] = "Vasya17";
names[18] = "Vasya19";
for (int i = 0; i < names.length; i++) {
if (names[i] == null) {
continue;
}
System.out.println(names[i]);
if (names[i].equals("Matilda"))
break;
}
System.out.println("Finish");
}
}