2013-12-08 26 views
1

行,所以我必須做出consoleprint接口類和實現它從具有工具

一類簡單地讓我打印文本的其他兩個類和其他ü可以看到的是兩個不同的類中調用方法字符串分離器。到目前爲止,我有問題,我的測試

public interface ConsolePrint { 

    public void printInfo(String infoToPrint); 

} 

public class SimplePrint implements ConsolePrint { 

    public void printInfo (String infoToPrint) { 
     printInfo("Heading this is not fancy"); 
    } 
} 

public class FancyPrint implements ConsolePrint { 

    public void printInfo (String printInfo) { 
     for (String splitter: printInfo.split("", 1)){ 
      System.out.println(splitter); 
      } 
    } 
} 

繼承人的測試,我從

import java.util.*; 

public class ConsolePrintTest { 

    public static void main(String[] args) { 
    } 

    SimplePrint mySp = new SimplePrint(); 
    FancyPrint myFp = new FancyPrint(); 

    myFp.printInfo(); <-----error appearing here 

} 

越來越問題

任何幫助將是巨大的感謝

+3

'SimplePrint.printInfo'是無限遞歸。 –

+0

_你有什麼錯誤? –

回答

3

您需要在方法調用進入你main方法(或至少一些方法)。目前它不在方法中 - 只有聲明(字段,方法,嵌套類型等)可以位於類的頂層。

此外,您目前沒有傳遞參數給printInfo方法,但

因此,這將是罰款:

public class ConsolePrintTest { 
    public static void main(String[] args) { 
     FancyPrint myFp = new FancyPrint(); 

     myFp.printInfo("some string"); 
    } 
} 

需要注意的是:

  • 我已經刪除因爲它是無關緊要的類的進口
  • 我已經刪除了mySp聲明作爲變量e從未使用過
  • 您目前沒有使用類實現接口的事實。你可能要考慮:

    ConsolePrint printer = new FancyPrint(); 
    printer.printInfo("some string"); 
    

正如在評論中指出,您的SimplePrint無條件執行遞歸太多,所以這是巢問題解決。

+0

感謝您的回覆 我需要打印的標題是不是從簡單的打印類花哨 公共類ConsolePrintTest { \t公共靜態無效的主要(字串[] args){ \t \t SimplePrint mySp =新SimplePrint( ); \t \t FancyPrint myFp = new FancyPrint(); \t \t mySp.printInfo(); \t \t myFp.printInfo(); \t} } – user3079838

+0

@ user3079838:我根本不理解您的評論,恐怕 - 特別是因爲printInfo採用字符串參數,並且評論中的代碼沒有提供。但請不要關注那部分 - 重點關注之前代碼中的錯誤。如果您對* *有疑問,請在評論中提問。如果您遇到*新問題,我建議您提出一個新問題。 –

1

移動聲明瞭一些方法內(在您的情況main):

public static void main(String[] args) { 


    SimplePrint mySp = new SimplePrint(); 
    FancyPrint myFp = new FancyPrint(); 

    myFp.printInfo("Test String"); //No error now 
} 
+0

@ user2336315:謝謝指出。我編輯了這篇文章。 –

0

您需要分析的參數到您的printInfo方法,因爲沒有方法沒有參數稱爲printInfo。

嘗試: myFP.printInfo(「Hello world」);

此外,您將得到另一個調用SimplePrint實現的錯誤,因爲它永遠不會停止遞歸調用相同的函數。

+0

對不起,我忘了包含mySp.printInfo(); – user3079838

+0

這需要打印來自課堂的文字「標題這不是花哨的」 – user3079838