java:不兼容的类型:java.lang.String无法转换为int

问题描述 投票:0回答:1

请告诉我如何正确使用此中断选项?

它告诉你

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");
    }
}

java arrays string equals
1个回答
0
投票

在 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");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.