简体   繁体   中英

returning ArrayList gives error: cannot find symbol

I am trying to return an ArrayList but at the very end i get error: cannot find symbol. I am adding to the list some Strings and Doubles and returning it to what called it.

error:

./Sample.java:55: error: cannot find symbol
        return placeMatch;
               ^
  symbol:   variable placeMatch
  location: class Sample
1 error

taking into consideration what was mentioned about the try catch i moved my declaration statement to the top and i get:

./Sample.java:54: error: incompatible types return placeMatch; ^ required: String found: ArrayList

actual code:

import java.util.ArrayList;
//...other imports

public class Sample
  extends UnicastRemoteObject
  implements SampleInterface {



    public Sample() throws RemoteException {

    }

    public String invert(String city, String state) throws RemoteException {
        try{


 ArrayList<Object> placeMatch = new ArrayList<Object>();
        // Read the existing address book.
        PlaceList place =
        PlaceList.parseFrom(new FileInputStream("places-proto.bin"));

        // Iterates though all people in the AddressBook and prints info about them.

        for (Place Placeplace: place.getPlaceList()) {
        //System.out.println("STATE: " + Placeplace.getState());
            if(Placeplace.getName().startsWith(city)){
                placeMatch.add(Placeplace.getName());
                placeMatch.add(Placeplace.getState());
                placeMatch.add(Placeplace.getLat());
                placeMatch.add(Placeplace.getLon());
                break;
            }


          }

        }catch(Exception e){
               System.out.println("opening .bin failed:" + e.getMessage());
        }
        return placeMatch;
    }

}

You need to declare:

ArrayList<Object> placeMatch = new ArrayList<Object>();

outside the try block.

Second question:

The method return type is String . You cannot return ArrayList<Object> .

The solution depends on what you need to do. You can change the return type:

public List<Object> invert(String city, String state) throws RemoteException {

The parameter placeMatch is visible only in the try block. So if you want to initialize and declare this parameter in try block, you should return this parameter at the bottom of try block and in the catch block return null or something. BUT! If you could, declare this param outside try block, as a instance variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM