有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中,如何在整个代码中使用一个变量的值?

使用While循环将文件中的行数存储在“c”变量中,但以后无法使用该变量

我试过使用下面的代码,但它在for循环中的字符“c”上给出了类似符号not fund的错误

int i = 0;

while ((line = reader.readLine()) != null ) {
    int c = ++i;
    System.out.println("Count of records " + i +": " + c);
}

for (int j = 0; j < c; ++j) {    
    System.out.println("Element at index " + j +": " + columns[j]);
}

共 (1) 个答案

  1. # 1 楼答案

    您需要在循环外声明c变量

    int i = 0, c = 0;
    
    while ((line = reader.readLine()) != null ) {
        c = ++i;
        System.out.println("Count of records " + i +": " + c);
    }
    for (int j = 0; j < c; ++j) {    
        System.out.println("Element at index " + j +": " + columns[j]);
    }