2013-03-21 118 views
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]; 
          } 
         } 
        } 

在文件中找到的数据的一个例子是“咖啡://本地主机/ BREW”,所以它并不总是在阵列中使用的5个指标。

+1

而不是那个巨大的if语句,你可以使用'URL [URL.length - 1]'获得数组的最后一个元素。 – Jeffrey 2013-03-21 00:40:45

+0

@杰弗里我不明白。我不需要一个巨大的if语句使用你的方法吗? – spogebob92 2013-03-21 00:44:57

+1

你为什么?任何Java数组中最后一个可访问的索引将是'Array.length - 1'。 – Jeffrey 2013-03-21 00:46:56

回答

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]到获取数组的最后一个元素。