2017-05-29 66 views
-3

我的程序将逐行读取文件,然后按分隔符分割行| (垂直线)并存储到String []中。但是,由于行中的列位置和列数将在未来发生变化,而不是使用具体的索引号0,1,2,3 ...,所以我使用索引++来迭代行分割记号;可变增量(索引++)不会每次增加1

运行该程序后,而不是增加1,每次索引将增加超过1。

我的代码如下如下:

BufferedReader br = null; 
String line = null; 
String[] lineTokens = null; 
int index = 1; 
DataModel dataModel = new DataModel(); 
try { 
    br = new BufferedReader(new FileReader(filePath)); 
    while((line = br.readLine()) != null) { 
     // check Group C only 
     if(line.contains("CCC")) { 
      lineTokens = line.split("\\|"); 
      dataModel.setGroupID(lineTokens[index++]); 
      //System.out.println(index); The value of index not equal to 2 here. The value change each running time 
      dataModel.setGroupName(lineTokens[index++]); 
      //System.out.println(index); 
      // dataModel.setOthers(lineTokens[index++]); <- if the file add columns in the middle of the line in the future, this is required. 
      dataModel.setMemberID(lineTokens[index++]); 
      dataModel.setMemberName(lineTokens[index++]); 
      dataModel.setXXX(lineTokens[index++]); 
      dataModel.setYYY(lineTokens[index++]); 
      index = 1; 
      //blah blah below 
     } 
    } 
    br.close(); 
} catch (Exception ex) {  
} 

的文件格式是这样如下:

 
Prefix | Group ID | Group Name | Memeber ID | Member Name | XXX | YYY 
GroupInterface | AAA | Group A | 001 | Amy | XXX | YYY 
GroupInterface | BBB | Group B | 002 | Tom | XXX | YYY 
GroupInterface | AAA | Group A | 003 | Peter | XXX | YYY 
GroupInterface | CCC | Group C | 004 | Sam | XXX | YYY 
GroupInterface | CCC | Group C | 005 | Susan | XXX | YYY 
GroupInterface | DDD | Group D | 006 | Parker| XXX | YYY 

反而增加1,指数++将增加超过1。我不知道为什么这个发生和如何解决它?任何帮助,高度赞赏。

+1

*“索引++将增加超过1”*,否则不会。 'index ++'破坏的可能性极小。 – Tom

+2

不应该'索引'从'0'开始? –

+0

您正在运行调试器? – Jens

回答

0

好,@SomeProgrammerDude狡猾地暗示,但我就站出来说:当你重新index它应被设置为,而不是1

通过从1开始index,你总是在你应该在的位置之前索引一个位置,并且你最终可能会获得空的catch条款所吞噬的IndexOutOfBoundsException