【问题标题】:How can I access an ArrayList that was created within an 'if' statement? [closed]如何访问在“if”语句中创建的 ArrayList? [关闭]
【发布时间】:2012-11-13 11:44:21
【问题描述】:

有人可以帮助我吗,我试图在声明它的 if 语句之外使用名为 prop 的数组列表,并在其中添加了一个对象。

这是 if 语句。代码要求用户输入信息,然后声明一个 Property 对象和一个 ArrayList 属性,它将我创建的属性对象添加到 ArrayList 中。

if(option.equals("one")){

    int x = 1;
    do{
        try{
            System.out.println("Enter owner name");
            String ownerName = scan.nextLine();
            System.out.println("Enter address");
            String address = scan.nextLine();
            System.out.println("Are you the principle private residant?");
            String principlePrivateResidance = scan.nextLine();
            System.out.println("Enter property location(city, large town, small town, vilage, countryside) ");
            String location = scan.nextLine();
            System.out.println("would you like to pay the propery tax now?(yes//no)");
            String paid = scan.nextLine();
            System.out.println("Enter your filename");
            String fn = scan.nextLine();
            System.out.println("Enter the estimated property value");

            int propertyEstimatedVal = scan.nextInt();
            // i make the object here 
            Property property = new Property(ownerName, address, paid, principlePrivateResidance,location, propertyEstimatedVal);

            // Then make the arraylist and add the object to it take this arraylist and put it....

            ArrayList<Property> prop = new ArrayList<Property>;
            prop.add(property);
            CalculateTax tax = new CalculateTax(property.getLocation(),property.getPrinciplePrivateResidance(),property.getPropertyEstimatedVal(), property.getPaid());

            System.out.println("owner:" + property.getOwnerName());
            System.out.println("address:" +property.getAddress());
            System.out.println("propertyEstimatedVal:" +property.getPropertyEstimatedVal());
            System.out.println("principlePrivateResidance:" +property.getPrinciplePrivateResidance());
            System.out.println("location:" +property.getLocation());
            System.out.println("paid:" +property.getPaid());
            System.out.println("Your property tax is" + CalculateTax.getSumoftax() );
            System.out.println("your details have been taken");

            FileWriter fstream = new FileWriter(fn,true);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(property.getOwnerName() + " | " + property.getAddress() + " | " + property.getPropertyEstimatedVal() + " | " + property.getPrinciplePrivateResidance() + " | " + property.getLocation() + " | " + property.getPaid() + " | " + CalculateTax.getSumoftax());
            out.newLine();
            out.close();
            x= 2;
        }
        catch(Exception e){
            System.out.println("error has occured");
        }
    }
    while(x == 1);

}
else if(option.equals("two")){
    // this just opens a file
    System.out.println("Please enter you file name");
    String filename = scan.nextLine();

    try{
        // Open the file that is the first
        // command line parameter
        FileInputStream fstream = new FileInputStream(filename);
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;

        //Read File Line By Line
        while ((strLine = br.readLine()) != null)   {
            // Print the content on the console
            System.out.println (strLine);
        }
        //Close the input stream
        in.close();
    }
    catch (Exception e){//Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }
}
else if(option.equals("three")){
    //i need to get that arraylist with the objects i added to it here but
    //i just dont know how
    System.out.print("Service is currently available ");

}
else{
    System.exit(0);
}

【问题讨论】:

  • 我不明白你的问题。请对其进行编辑以澄清您遇到的确切问题。
  • 你需要在足够高的范围内声明你的变量,以便它对你的类的所有需要​​它的部分都是可见的。这通常意味着将其声明为类变量,但也可能只需要在方法顶部声明该变量。因为你的代码很难阅读,所以我不能肯定地说你需要在哪里放置变量。请格式化并重新发布。
  • 您的一个分支创建了 ArrayList,而另一个分支尝试访问它——这怎么可能?代码看起来像您要么创建列表使用它。
  • 对不起,我花了半个小时试图发布它,我需要使用 arraylist 和我在 if 语句之外添加到它的对象
  • 应该是 ArrayList prop = new ArrayList;

标签: java if-statement arraylist scope


【解决方案1】:

如果您需要在if 语句之外访问ArrayList,您需要将变量声明移到if 语句之前。比如这里去掉这行...

Property property = new Property(ownerName, address, paid, principlePrivateResidance,location, propertyEstimatedVal);

// Then make the arraylist and add the object to it take this arraylist and put it....

ArrayList<Property> prop = new ArrayList<Property>; // REMOVE THIS LINE
prop.add(property);

然后在此处添加它...

ArrayList<Property> prop = new ArrayList<Property>; // ADD THIS LINE

if(option.equals("one")){

    int x = 1;
    do{

现在ArrayList 定义在if 语句之前,因此您可以在if 语句内外的任何位置使用它。

无论如何,您可能希望将ArrayList 移到do-while 循环之外,否则每次通过do-while 循环时都会创建一个新的ArrayList。我确定您真正想要的是创建一个 ArrayList 并添加一些项目 - 因此您需要将 ArrayList 的声明移到 do-while 循环之外,这也可以通过我上面的代码更改了。

您需要做的下一件事是检测项目是否已添加到您的ArrayList。如果您不执行if(option.equals("one")){ 语句中的代码,则不会向ArrayList 添加任何内容,因此它将为空。因此,如果您以后想使用您的ArrayList,您应该首先检查其中是否有任何项目,如果它们存在则使用它们 - 可能是这样的......

if (prop.size() > 0){
    // there are items
    doSomething();
}
else {
    // no items
    doSomethingElse();
}

【讨论】:

    【解决方案2】:

    您需要将您的数组列表 decalration/insntantiation 移到您的 if 语句之外,如下所示:

            List<Property> prop = new ArrayList<Property>;
    
            if(option.equals("one")){
                 //your if block code
                do{
                   //rest of your code except list declaration/initialization
                  }while(x==1);
                  ....
            }else if(option.equals("two")){
               .....
            } else if(option.equals("three")){
               //your list `prop` is available here
               ....
            }
    

    这是必需的,原因有两个:

    1. 目前,您正在 do-while 循环的每次迭代中重新实例化道具列表,并丢失之前添加的数据。
    2. 只有当您需要在 if 之外(即在 else 块中)访问它时,您的列表才在 if 块的范围内。

    通过将列表初始化移到 if 块之外,您将解决这两个问题。

    【讨论】:

      猜你喜欢
      • 2019-07-03
      • 1970-01-01
      • 2019-06-02
      • 1970-01-01
      • 2012-10-20
      • 1970-01-01
      • 2020-03-30
      • 1970-01-01
      • 2018-12-26
      相关资源
      最近更新 更多