如何使用在if
块之外的if
语句内声明的变量?如何使用if语句之外的if语句中声明的变量?
if(z<100){
int amount=sc.nextInt();
}
while(amount!=100)
{ //this is wrong.it says we cant find amount variable ?
something
}
如何使用在if
块之外的if
语句内声明的变量?如何使用if语句之外的if语句中声明的变量?
if(z<100){
int amount=sc.nextInt();
}
while(amount!=100)
{ //this is wrong.it says we cant find amount variable ?
something
}
你不能,它只能限制在if块中,或者使它的作用域更明显,比如声明它在外面,如果在该作用域内使用它。在Java中
int amount=0;
if (z<100) {
amount=sc.nextInt();
}
while (amount!=100) { // this is right.it will now find amount variable ?
// something
}
检查here有关变量的作用域
为了使用amount
在外部范围需要声明它if
块之外:
int amount;
if (z<100){
amount=sc.nextInt();
}
为了能够阅读它的值还需要确保它在所有路径中分配了一个值。您还没有表现出要如何做到这一点,但一个选择是使用0
int amount = 0;
if (z<100) {
amount = sc.nextInt();
}
它的默认值,或者更简洁使用条件运算符:
int amount = (z<100) ? sc.nextInt() : 0;
的amount
范围被束缚在花括号内,所以你不能在外面使用它。
解决的办法是把它当块之外(请注意,amount
不会被发送,如果如果条件不满足):
int amount;
if(z<100){
amount=sc.nextInt();
}
while (amount!=100){ }
或者你打算让while语句是内部的,如果:
if (z<100) {
int amount=sc.nextInt();
while (amount!=100) {
// something
}
}
了解更多关于变量的作用域:http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm –