JAVA零基础小白自学日志——第十五天


今日提要:程序分析

先来看看官方代码,我写代码的时候没看官方代码

上一篇日志的那道题引用自《Head First Java》
它的代码里面使用了动态列表,比我使用的数组还是要灵活和效率很多,而且直观第一眼看去,面向对象的核心思想贯彻的比我的好得多

1.官方代码

import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class StartupBust {

  private GameHelper helper = new GameHelper();
  private ArrayList<Startup> StartupsList = new ArrayList<Startup>();
  private int numOfGuesses = 0;

  private void setUpGame() {
    // first make some Startups and give them locations
    Startup one = new Startup();
    one.setName("poniez");
    Startup two = new Startup();
    two.setName("hacqi");
    Startup three = new Startup();
    three.setName("cabista");
    StartupsList.add(one);
    StartupsList.add(two);
    StartupsList.add(three);

    System.out.println("Your goal is to sink three Startups.");
    System.out.println("poniez, hacqi, cabista");
    System.out.println("Try to sink them all in the fewest number of guesses");

    for (Startup StartupToSet : StartupsList) {
      ArrayList<String> newLocation = helper.placeStartup(3);
      StartupToSet.setLocationCells(newLocation);
    } // close for loop
  } // close setUpGame method

  private void startPlaying() {
    while (!StartupsList.isEmpty()) {
      String userGuess = helper.getUserInput("Enter a guess");
      checkUserGuess(userGuess);
    } // close while
    finishGame();
  } // close startPlaying method


  private void checkUserGuess(String userGuess) {
    numOfGuesses++;
    String result = "miss"; // assume a miss until told otherwise

    for (int i = 0; i < StartupsList.size(); i++) {

      Startup StartupToTest = (Startup) StartupsList.get(i);
      result = StartupToTest.checkYourself(userGuess);

      if (result.equals("hit")) {

        break;
      }
      if (result.equals("kill")) {

        StartupsList.remove(i); // he's gone
        break;
      }

    } // close for

    System.out.println(result);
  }


  private void finishGame() {
    System.out.println("All Startups are dead! Your stock is now worthless");
    if (numOfGuesses <= 9) {
      System.out.println("It only took you " + numOfGuesses + " guesses.  You get the Enron award!");
    } else {
      System.out.println("Took you long enough. " + numOfGuesses + " guesses.");
      System.out.println("Too bad you didn't get out before your options sank.");
    }
  }


  public static void main(String[] args) {
    StartupBust game = new StartupBust();
    game.setUpGame();
    game.startPlaying();
  }
}

class Startup {
	private ArrayList<String> locationCells;
    // private int numOfHits = 0;
    // don't need to track this now
    private String name;

    //public void setLocationCells(ArrayList<String> locs) {
       // locationCells = locs;
   // }
    public void setLocationCells(ArrayList<String> loc) {
        locationCells = loc;
    }

    public void setName(String n) {
        name = n;
    }

    public String checkYourself(String userInput) {
    	String result = "miss";
	    int index = locationCells.indexOf(userInput);
	    if (index >= 0) {
        locationCells.remove(index);
        if (locationCells.isEmpty()) {
            result = "kill";
            System.out.println("Ouch! You sunk " + name + "   : ( ");
        } else {
            result = "hit";
        } // end if
        } // end outer if
        return result;
    } // end method
} // close class

class GameHelper {

	  private static final String alphabet = "abcdefg";
	  private int gridLength = 7;
	  private int gridSize = 49;
	  private int[] grid = new int[gridSize];
	  private int comCount = 0;

	  public String getUserInput(String prompt) {
	    String inputLine = null;
	    System.out.print(prompt + "  ");
	    try {
	      BufferedReader is = new BufferedReader(
	              new InputStreamReader(System.in));
	      inputLine = is.readLine();
	      if (inputLine.length() == 0) {
	        return null;
	      }
	    } catch (IOException e) {
	      System.out.println("IOException: " + e);
	    }
	    return inputLine.toLowerCase();
	  }

	  public ArrayList<String> placeStartup(int comSize) {
	    ArrayList<String> alphaCells = new ArrayList<String>();
	    // holds ‘f6' type coords
	    String temp = null;                                // temporary String for concat
	    int[] coords = new int[comSize];                  // current candidate coords
	    int attempts = 0;                                  // current attempts counter
	    boolean success = false;                           // flag = found a good location ?
	    int location = 0;                                  // current starting location

	    comCount++;                                        // nth Startup to place
	    int incr = 1;                                      // set horizontal increment
	    if ((comCount % 2) == 1) {                         // if odd Startup (place vertically)
	      incr = gridLength;                               // set vertical increment
	    }

	    while (!success & attempts++ < 200) {             // main search loop  (32)
	      location = (int) (Math.random() * gridSize);     // get random starting point
	      //System.out.print(" try " + location);
	      int x = 0;                                       // nth position in Startup to place
	      success = true;                                 // assume success
	      while (success && x < comSize) {                // look for adjacent unused spots
	        if (grid[location] == 0) {                    // if not already used

	          coords[x++] = location;                    // save location
	          location += incr;                          // try ‘next' adjacent
	          if (location >= gridSize) {                 // out of bounds - ‘bottom'
	            success = false;                         // failure
	          }
	          if (x > 0 && (location % gridLength == 0)) {  // out of bounds - right edge
	            success = false;                         // failure
	          }
	        } else {                                      // found already used location
	          // System.out.print(" used " + location);
	          success = false;                          // failure
	        }
	      }
	    }                                                   // end while

	    int x = 0;                                          // turn location into alpha coords
	    int row = 0;
	    int column = 0;
	    // System.out.println("\n");
	    while (x < comSize) {
	      grid[coords[x]] = 1;                              // mark master grid pts. as ‘used'
	      row = (int) (coords[x] / gridLength);             // get row value
	      column = coords[x] % gridLength;                  // get numeric column value
	      temp = String.valueOf(alphabet.charAt(column));   // convert to alpha

	      alphaCells.add(temp.concat(Integer.toString(row)));
	      x++;
	      // System.out.print("  coord "+x+" = " + alphaCells.get(x-1));
	    }

	    // System.out.println("\n");

	    return alphaCells;
	  }
	}

2.我的代码

官方代码解读,分步的测试,还有就是动态列表的运用,逻辑表达更加清晰,应该说官方的效率应该更高,代码更健壮些,这些还需要各种练习,没有别的取巧的地方。

  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值