说到for循环
,我想要一个for循环
内的动态条件。为了更清楚地说明,这是我为您提供的代码:
FileOutputStream Fcategorize = new FileOutputStream(write, true);
FileReader inputFile = new FileReader(wrote);
BufferedReader bufferReader = new BufferedReader(inputFile);
String line;
for (int i = 0; (line = bufferReader.readLine()) != null; i++) {
if ("this2".equals(line)) {
while (!"this3".equals(line = bufferReader.readLine())) {
Fcategorize.write(line.toLowerCase().getBytes());
Fcategorize.write(
System.getProperty("line.separator").getBytes());
}
}
}
但是,我想要的是 this2
和 this3
在每次迭代中都根据 i
的值更改其整数属性。怎么可能?
编辑:
示例文件内容:
this2
primarygames
storybooks
bookshelf.htm
this3
classzone
books
research_guide
page_build.cfm
this4
grandmasandy
books-info.html
this5
soiwasthinkingaboutadoption
free_book.html
this6
slcpd
c0ntent
uploads
activity-book.pdf
this7
一个干净的解决方案可能会使用一种方法来根据当前行或组号来计算要匹配的字符串。
static String header( int i ){ return "this" + (i+2); // "this2" for i == 0 }static String body( int i ){ return "this" + (i+3); // "this3" for i == 0 }
读取循环变为
String line = bufferReader.readLine();for(int i = 0; line != null; i++){ if( header(i).equals(line)){ while( (line = bufferReader.readLine()) != null && ! body(i).equals( line ) ){ Fcategorize.write(...); Fcategorize.write(...); } }}
请注意,我还在内部循环中添加了对 EOF 的检查。
如果您确实想让字符串组成一致,请使用
if( ("this" + (i+2)).equals( line ) ){...}
或者,因为如果保护得当,行永远不会为空
if( line.equals( "this" + (i+2) ) ){...}
算术加法必须具有更高的优先级;否则它将连接到“this02”、“this12”等。
编辑 该算法本质上是危险的,因为如果第一行不包含“this2”,它可能会进入无限循环。最好在一个循环中读取并测试该行,看看你在哪里。
String line;int expect = 0;int body = 0;while( (line = bufferReader.readLine()) != null ){ if( line.equals( header(expect) ) ){ body = expect; expect++; } else if( body > 0 ) { Fcategorize.write(...); // process body }}
我是一名优秀的程序员,十分优秀!