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

在Java中,如何在整个代码中使用一个变量的值?,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)

使用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]);
}
inti=0;
而((line=reader.readLine())!=null){
int c=++i;
System.out.println(“记录计数”+i+:“+c”);
}
对于(int j=0;j
您需要在循环外声明
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]);
}
inti=0,c=0;
而((line=reader.readLine())!=null){
c=++i;
System.out.println(“记录计数”+i+:“+c”);
}
对于(int j=0;j
您需要在循环外声明
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]);
}
inti=0,c=0;
而((line=reader.readLine())!=null){
c=++i;
System.out.println(“记录计数”+i+:“+c”);
}
对于(int j=0;j
这里的概念是“可变范围”。变量只能在其范围内使用或访问。局部变量的范围始终限于定义它们的代码块。块是大括号内的代码区域。在这些大括号之外,局部变量不再存在。因此,要扩展局部变量的范围,请将其定义从其代码块移动到下一个代码块之外的代码块。这里的概念是“变量范围”。变量只能在其范围内使用或访问。局部变量的范围始终限于定义它们的代码块。块是大括号内的代码区域。在这些大括号之外,局部变量不再存在。因此,若要扩展局部变量的范围,请将其定义从其代码块移动到位于外部的下一个代码块。