'integer.parseint'에 해당되는 글 1건

  1. 2013.01.18 Head First Java - 5장 메소드를 더 강력하게, SimpleDotComTestDrive.java
반응형

 

import java.io.*;

 

public class SimpleDotComTestDrive {
 
 public static void main(String[] args) {
  
    int numOfGuesses = 0;
    GameHelper helper = new GameHelper();
   
    SimpleDotCom theDotCom = new SimpleDotCom();
    int randomNum = (int)(Math.random()*5);
   
    int[] locations = {randomNum,randomNum+1,randomNum+2};
    theDotCom.setLocationCells(locations);
    boolean isAlive = true;
   
    while(isAlive == true) {
     
      String guess = helper.getUserInput("enter a number");     
      String result = theDotCom.checkYourself(guess);
      numOfGuesses++;
     
      if(result.equals("kill")) {
        isAlive = false;
        System.out.println(numOfGuesses + " guesses");
    } // if문 끝
 } // while문 끝
 } // main문 끝
} // class문 끝

 

 

class SimpleDotCom {
 
 int[] locationCells;
 int numOfHits = 0;

 public void setLocationCells(int[] locs) {
  locationCells = locs;
 }

 public String checkYourself(String stringGuess) {
  int guess = Integer.parseInt(stringGuess);
  String result = "miss";
  for(int i=0; i < locationCells.length; i++) {
    if(guess == locationCells[i]) {
   result = "hit";
   numOfHits++;
   break;
    }
 }

 if(numOfHits == locationCells.length) {
  result="kill";
 }

 System.out.println(result);
  return result;
 }
}


class GameHelper {
  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;
    }
}

 

//String을 int로 바꿀 대는 Integer.parseInt()를 쓴다.
//String Str = "1000";
//int nmbr = Integer.parseInt(Str);

//p.141
//Math.random은 double형의 0이상 1미만의 숫자를 리턴한다.

반응형