2011-06-05 60 views
0

我正在嘗試取文本字段的值,並將其應用於方法以便爲該值搜索文本文件。但在我的方法中,我顯示一個丟失的返回值錯誤,似乎無法使其工作。下面是我的代碼:遺失退貨聲明

 submitsearch.addActionListener(new ActionListener() 
     { 
     public void actionPerformed(ActionEvent e) 
     { 

      whatToSearch = searchfield.getText(); 
       result = SearchString(whatToSearch); 




     } 
    }); 
} 

public String SearchString(String result) 
{ 
    String input; 

    try{ 
     String details, id, line; 
     int count; 
     Scanner housenumber = new Scanner(new File("writeto.txt")); 
     while(housenumber.hasNext()) 
     { 
      id = housenumber.next(); 
      line = housenumber.nextLine(); 
      { 

       if(!housenumber.hasNext()) 
       JOptionPane.showMessageDialog(null,"No Properties with this criteria"); 
      } 

      if(result.equals(id)); 
      { 
       JOptionPane.showMessageDialog(null,id + line); 
      } 

     } 
    } 

    catch(IOException e) 
    { 
     System.out.print("File failure"); 
     } 
    } 
} 

附錄:

在SearchString在我希望搜索我的文本文件在一個JOptionPane的顯示在我的文本框輸入的值。雖然我現在有return語句,當我點擊搜索我被一個,無論它們是否匹配我的搜索

+0

您的'SearchString'方法不會在任何地方返回一個值,但您已指定它應該返回一個'String'。 – 2011-06-05 16:38:57

+1

真正的問題是,它不清楚你在'SearchString'中試圖完成什麼。也許如果你描述輸入和期望的結果,你可以得到一個有用的答案。 – 2011-06-05 16:39:44

+0

在SearchString我希望能夠搜索我的文本文件輸入在我的文本字段中的值顯示它在一個JOptionPane。雖然我現在有返回聲明,當我點擊搜索時,我會在JOptionPanes中逐一顯示所有記錄,無論它們是否與我的搜索匹配。 – 2011-06-05 16:44:58

回答

3

在catch塊後添加return null;

方法簽名說它返回一個字符串。這意味着無論您的代碼需要什麼流程,該方法都應該返回一個值。但是,當發生異常時,不會有任何回報。因此,您必須在發生異常時指定返回值

6

您已聲明與String返回類型的功能中顯示的所有記錄在JOptionPanes之一,因此它必須返回所有代碼路徑上的String。如果您不需要返回任何內容,請改用void

+0

我只是想強調**所有代碼路徑**部分。因爲你有一個try-catch結構並且不在catch塊中拋出異常,所以這被認爲是不同的路徑。當你添加你的return語句時,或者把它放在try-catch塊之外(首選),或者如果你在你的try塊中放入一個return,你也需要在你的catch塊中使用一個。 – 2011-06-05 17:08:32