2012-11-08 129 views
2

如何使用在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 
} 
+2

了解更多关于变量的作用域:http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm –

回答

4

你不能,它只能限制在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有关变量的作用域

5

为了使用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; 
8

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 
    } 

} 
+0

这不实际工作,因为量变量并不总是分配,其他答案比较好。 – EdC

+0

@EdC如果不理解OP的问题,很难说“实际”会起什么作用。希望这个答案能够解释这个问题。 – Pubby