0

我正在尝试创建一个程序,它将读取一个文件,将该文件拆分为一个数组,只要有一个“/”,然后将变量“theOutput”设置为数组中索引的值。麻烦的是,索引总是等于null。这是我的代码:

String theOutput = null;
        String content = new Scanner(new File("URL.txt")).useDelimiter("\\Z").next();
        theInput = content;
        String[] URL = theInput.split("/");
        System.out.println(theInput);
        System.out.println(URL.length);




            if (URL.length == 1) {
                theOutput = URL[0];
                if (URL.length == 3) {
                    theOutput = URL[2];
                    if (URL.length == 4) {
                        theOutput = URL[3];
                        if (URL.length == 5) {
                            theOutput = URL[4];
                            if (URL.length == 6) {
                                theOutput = URL[5];
                            }
                        }
                    }

在文件中找到的数据示例是“coffee://localhost/brew”,因此它并不总是在数组中使用 5 个索引。

4

1 回答 1

1

您的 if 语句相互嵌套,因此if(URL.length == 3)仅当 URL 的长度为 1 时才会运行。因此,您应该执行以下操作:

if(URL.length == 1){
    theOutput = URL[0];
}
if(URL.length == 2){
    theOutput = URL[1]
}
//etc.

或者,您可以说theOutput = URL[URL.length-1]获取数组的最后一个元素。

于 2013-03-21T00:46:28.153 回答