Java 从括号段中提取变量

Java 从括号段中提取变量,java,Java,我得到了一个while语句,其中包含许多不同的if语句,它们将数组中的值相加。数组中的值已从文件中提取 int variable 1 int variable 2 while(scanner.next()) { if variable 1 { } if variable 2 { } } 每行的值相加,仅显示该行的总计。我想把每一行的总值加起来,得到一个总的总数 问题是,当我试图在结束while括号后使用变量1或2时,我得到了一个错误。我猜想这是因为它与while语句不在同一块中?我如

我得到了一个while语句,其中包含许多不同的if语句,它们将数组中的值相加。数组中的值已从文件中提取

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

 }
if variable 2 {

}

}
每行的值相加,仅显示该行的总计。我想把每一行的总值加起来,得到一个总的总数

问题是,当我试图在结束while括号后使用变量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);

随手算数,而不是事后算数

int total = 0;

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

 }
System.out.println(total);

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

因此,当您在块内定义新变量时,它将仅在该块的作用域(及其子作用域)上活动(或访问),而不被外部作用域激活(或访问)

请看一下这个,特别是局部变量部分

例子
将不起作用:

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
这将
起作用:

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和2在前面定义,而{…}和total在后面定义)来看,它应该可以工作。请发布一个真实再现错误的示例。请阅读Java教程。总体而言,变量1+2显示错误“无法解析为变量”@Breaker为记录,变量名不能包含空格hanks为提示。习惯上我不使用空格,但如果我使用过,我会知道原因。这段代码不可编译,所以对于那些似乎在为基础知识而挣扎的人来说,这不是一个很好的例子……谢谢。我尝试过这样做,但是我得到了相同的错误,因为println在while块之外。@DavidPostill作为伪代码,这是非常好的,这是他提供的(如原始问题)。