使用.split方法和JOP.InputDialog Java

时间:2018-10-16 02:29:13

标签: java exception-handling nullpointerexception

因此,这是一个uni项目的代码段,对于Java来说还算是新手,所以请原谅任何可怜的代码。限制之一是代码在退出/取消时一定不能有错误。因此,我知道JOptionPane.showInputDialog上的“取消”按钮返回null,但是“ parts = temp.split(“”)'的部分似乎是出于我不知道的原因阻止输入为null?当我摆脱了parts = temp.split()时,选择取消按钮时不会抛出异常,但是显然for循环不起作用。所以我需要做的是没有异常或错误产生取消。任何帮助将不胜感激! :) **编辑**我们也禁止使用catch,try或break任何while循环。必须以true / false退出。

    while (X == true && flag == true) {
        input = JOptionPane.showInputDialog("Tell me more about " + topics[z]);
        String temp = input;
        if (input != null) {
            flag = true;
        }
        else if (input == null) {
            flag = false;
        }

        parts = temp.split(" ");

        for (int i = 0; i < parts.length; i++) {
            for (int x = 0; x < topics.length; x++) {
                if (parts[i].equals(topics[x])) {
                    cut = parts[i];
                    break;
                }
            }
        }
        for (int i = 0; i < topics.length; i++) {
            if (cut.equals(topics[i])) {
                z = i;
                break;
            }

        }

        input = cut;
        System.out.print(cut);
        System.out.println(z);

        X = Arrays.asList(topics[z]).contains(input);
        System.out.println(X);

    }

1 个答案:

答案 0 :(得分:0)

您还需要在parts = temp.split(" ");内编写if (input != null),并确保parts在此之前已初始化;否则,您也会在NPE行中看到parts.length。 我假设topics不为空:

while (X == true && flag == true) {
        input = JOptionPane.showInputDialog("Tell me more about " + topics[z]);
        String temp = input;
        parts = new String[initialArraySize];

        if (input != null) {
            parts = temp.split(" ");
            flag = true;
        }
        else if (input == null) {
            flag = false;
        }



        for (int i = 0; i < parts.length; i++) {
            for (int x = 0; x < topics.length; x++) {
                if (parts[i].equals(topics[x])) {
                    cut = parts[i];
                    break;
                }
            }
        }
        for (int i = 0; i < topics.length; i++) {
            if (cut.equals(topics[i])) {
                z = i;
                break;
            }

        }

        input = cut;
        System.out.print(cut);
        System.out.println(z);

        X = Arrays.asList(topics[z]).contains(input);
        System.out.println(X);

    }