从括号部分中提取变量

时间:2014-11-05 12:32:42

标签: java

我有一个while语句,其中包含许多不同的if语句,这些语句将数组中的值相加。数组中的值已从文件中提取。

int variable 1
int variable 2
while(scanner.next()) {
 if variable 1 {

 }
if variable 2 {

}

}

每行的值相加,仅显示该行的总数。我希望每行的总值加起来得出总数。

问题是当我在括号结束后尝试使用变量1或2时,我收到错误。我认为这是因为它与while语句不在同一个块中?我该如何解决这个问题?

这与我需要的相似:

 int variable 1
 int variable 2
 while(scanner.next()) {
 if variable {

 }
 if variable 2 {

 }

 }
int overall total = variable 1 + variable 2;
System.out.println(overalltotal);

2 个答案:

答案 0 :(得分:1)

Java中的括号定义了block。每个都有自己的scope,并且会继承父块的范围。

因此,当您在块中定义一个新变量时,该块的范围(及其子范围)上只有 alive (或 access ),并且而不是外部范围。

请查看此article,特别是 本地变量 部分。

实施例


不会工作:

if(something) { //Start of if scope

    //We create someVar on the if scope
    int someVar = 0;

} //End of if scope

System.out.println(someVar); //You can't access someVar! You are out of the scope

工作:

//We create someVar on the method's scope
int someVar = 0

if(something) { //Start of if scope

    //This "if scope" is a child scope, so it inherits parent's scope
    //Can access the parent scope
    someVar = 2;

} //End of if scope

System.out.println(someVar); //Can access someVar! It wasn't defined on a child scope

答案 1 :(得分:0)

在你去之后而不是事后总结。

int total = 0;

while(scanner.next()) {
 if int variable 1 {
    total += variable 1
 }
 if variable 2 {
    total += variable 2
 }

 }
System.out.println(total);