2013-10-31 35 views
0

我想返回一個ArrayList,但在最後我得到錯誤:無法找到符號。我在列表中添加了一些字符串和雙精度字符,並將其返回給它。返回ArrayList給出錯誤:找不到符號

錯誤:

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

考慮什麼提到關於嘗試捕捉我動了我的聲明語句頂端和我得到:

./Sample.java:54:錯誤:不兼容類型 return placeMatch; ^ 要求:字符串 發現:ArrayList的

實際代碼:

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; 
    } 

}

回答

8

需要聲明:

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

try塊之外。

第二個問題:

該方法返回類型是String。您不能退回ArrayList<Object>

解決方案取決於你需要做什麼。您可以更改退貨類型:

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

固定但我現在返回時得到不兼容的類型。更新的問題。 – user2644819

+0

更新我的回答 – BobTheBuilder

+0

如果我這樣做,然後我得到: 錯誤:無法找到符號 公開名單反轉(字符串市,字符串州)將拋出RemoteException { ^ 符號:類List 位置:類樣品 – user2644819

1

參數placeMatch僅在try塊中可見。所以如果你想在try塊中初始化並聲明這個參數,你應該在try塊的底部返回這個參數,並且在catch塊中返回null或者其他東西。但!如果可以的話,在try塊外面聲明這個參數,作爲一個實例變量。

+0

已修正,但現在返回時我得到不兼容的類型。更新的問題。 – user2644819

+0

在方法聲明(invert)中,你向你的機器保證你將返回一個String對象,但是你從Object類返回一個對象的ArrayList。這就是你的虛擬機很不高興的原因。在反轉方式降噪中改變返回類型 – k4sia