ブックの設計プロセス:
インスタンス変数とメソッド>デザインクラス - - >ライト擬似方法 - フローダイアグラム - >所望のクラス>書き込みテスト・コードを見つける - >実装クラス - >テストとエラー訂正
あなたはクラスを作成する前にそのテストクラスTestDriverを書く、その後、テストクラスに応じて特定のクラスを書きます
このゲームはSimpleDotCom、SimpleDotComGame、GameHelper三つのクラス、ファイルコンパイルされた.class 3つのクラスがゲームにSimpleDotComすることにより、他のクラスに同じディレクトリにmain()メソッドを呼び出すことができるようになりました
SimpleDotComTestDriver.java:
クラスSimpleDotCom { INT [] locationCells。 int型 numOfHits = 0 ; 公共 ボイド setLocationCells(INT [] LOCS){ locationCells = LOCS。 } パブリック文字列checkYourself(文字列stringGuess){ int型の推測= Integer.parseInt(stringGuess)。 文字列の結果 =「ミス」。 以下のための(int型セル:locationCells){ 場合(推測== セル){ 結果 = "ヒット" 。 numOfHits++ ; 休憩; } } もし(numOfHits == locationCells.length){ 結果 = "殺します" 。 } のSystem.out.println(結果)。 戻り値の結果; } } // SimpleDotCom的测试码 パブリック クラスSimpleDotComTestDriver { 公共 静的 ボイドメイン(文字列[]引数){ SimpleDotComドット = 新しいSimpleDotCom()。 INT []位置= {2,3,4 }。 dot.setLocationCells(位置) 文字列userGuess = "2" ; 文字列結果 = dot.checkYourself(userGuess)。 文字列testResult = "失敗" ; もし(result.equals( "ヒット" )){ testResult = "合格" ; } のSystem.out.println(testResult)。 } }
SimpleDotCom.java:
パブリック クラスSimpleDotCom { // インスタンス変数 INT [] locationCells; INT numOfHits = 0 ; // セッターメソッド 公共 ボイド setLocationCells(INT [] LOCS){ locationCells = LOCS; } //はの決意方法の結果ヒット パブリック文字checkYourself(文字列stringGuessを){ int型 GUESS = Integer.parseInt(stringGuess); 文字列結果 = "ミス" ; のための(int型セル:locationCells){ IF(GUESS ==細胞){ 結果 =「ヒット」。 numOfHits ++ ; 休憩; } } もし(numOfHits == locationCells.length){ 結果 = "殺します" 。 } のSystem.out.println(結果)。 戻り値の結果; } // メイン パブリック 静的 ボイドメイン(文字列[]引数){} }
GameHelper.java:
輸入 java.io. * ; パブリック クラスGameHelper { パブリック文字列getUserInput(文字列プロンプト){ 文字列inputLine = NULL ; System.out.print(プロンプト +」 " ); 試す{ BufferedReaderのある = 新しい BufferedReaderの(新しいInputStreamReaderの(System.in))。 inputLine = is.readLine()。 もし(inputLine.length()== 0)の戻り はnull ; } キャッチ(IOExceptionを電子){ System.out.println("IOExceptionが:" + e)前記 } 戻りinputLineと、 } パブリック 静的 ボイドメイン(文字列[]引数){} }
SimpleDotComGame.java:
パブリック クラスSimpleDotComGame { 公共 静的 ボイドメイン(文字列[]引数){ int型 numOfGuess = 0 ; // ゲーム対話プロンプト GameHelperヘルパー= 新しい新しいGameHelper(); //はドットコムは、オブジェクト作成 SimpleDotCom theDotCom = 新しい新しいSimpleDotCom(); int型 randomNum = (INT)(Math.random()* 5 ); // 初期化ドットコムオブジェクト のint [] = {randomNum場所、randomNum + 1、+ 2 randomNum。}; theDotCom.setLocationCells(場所)、 ブールのisAlive =真; // 游戏判断过程 一方(のisAlive == 真){ 文字列の推測 = helper.getUserInput( "番号を入力" )。 文字列結果 = theDotCom.checkYourself(推測)。 numOfGuess ++ ; もし(result.equals( "キル" )){ のisAlive = 偽。 System.out.println( + numOfGuess + "推測"を"あなたが撮りました" ); } } } }