java - 表达式条件的动态索引,例如 While、If 等

标签 java for-loop conditional-statements

说到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());
        }
    }

}

但是,我想要的是 this2this3 在每次迭代中都根据 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 
    }
}

关于java - 表达式条件的动态索引,例如 While、If 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33383787/

相关文章:

java - R.loess 和 org.apache.commons.math LoessInterpolator 的区别

java - 泛型和 Class.forName

javascript - 在 Node js 中 for 循环完成时调用函数

javascript - 第二个内含 IF 语句的嵌套循环 (FOR) 仅打印一个结果

vue.js - 一行条件在 Vue js 中的数据中不起作用

java - 如何在 mysql-connector-java 上允许 LOAD DATA LOCAL INFILE?

java nio 无法写入文件,旧式文件可以工作。怎么了?`

r - 在 R : script works, 中的移动日期窗口上缩放变量,但速度慢得令人无法接受。优化方法? rstats

c++ - 有条件地从文件中逐行读取

c# - 如果两个条件之一为真,则结束协程