如何在java中访问if语句之外的变量

时间:2010-12-28 02:46:06

标签: java variables

我在if语句中定义了一个变量,我现在尝试在if语句之外访问它。现在错误是说它找不到符号,因为它被定义为一个intance变量,有没有办法可以改变它,所以我可以在变量之外访问它?继承人的代码

if((e.getSource()==userOrder2)&& (orderType==1))
{
     String buyO= userOrder2.getText();
     int buyOrder= Integer.parseInt(buyO); //variable im trying to access
}

// trying to use buyOrder in a different if statement
if(orderType==1 && (stockPrice <= buyOrder))
{
     orderResult.setText("The Stock" + (stockName2.getText()) + "was bought at" + stockPrice);
}

4 个答案:

答案 0 :(得分:3)

使用可以将其用作

 int buyOrder= 0;
 if((e.getSource()==userOrder2)&& (orderType==1)){
     String buyO= userOrder2.getText();
     buyOrder= Integer.parseInt(buyO);
 }
 if(orderType==1 && (stockPrice <= buyOrder))

Java使用block级本地变量范围。必须在范围中声明变量,该范围对于您要使用它的所有位置都是通用的。

在您的情况下,变量buyOrder的范围仅限于块if((e.getSource()==userOrder2)&& (orderType==1)){...},因此在if块之外不可用。在这里,我们需要将变量声明在if((e.getSource()==userOrder2)&& (orderType==1)){...}之外,以便可以在块之外访问它。

答案 1 :(得分:1)

if语句之前(之前)声明它。

答案 2 :(得分:0)

在if语句之外声明。

int buyOrder;
if((e.getSource()==userOrder2)&& (orderType==1))
{
    String buyO= userOrder2.getText();
        buyOrder= Integer.parseInt(buyO); //variable im trying to access
}

  if(orderType==1 && (stockPrice <= buyOrder))

答案 3 :(得分:0)

boolean trouble = true;

int buyOrder;
if((e.getSource()==userOrder2)&& (orderType==1)) {
    String buyO= userOrder2.getText();
    buyOrder= Integer.parseInt(buyO); //variable im trying to access
    trouble = false;
}

if(orderType==1 && (stockPrice <= buyOrder)) {
 if (!trouble) {
  //Do what you need.
 } else {
  //Bail out.
 }
}