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

时间:2018-12-27 14:09:30

标签: java

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

我尝试使用下面的代码,但是它给出了错误,例如符号未在for循环中的字符“ c”上提供资金。

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 个答案:

答案 0 :(得分:4)

您需要在循环外声明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]);
}