자바 코드 질문 입니다.. 실행이 안되요..

자바 코드 질문 입니다.. 실행이 안되요..

작성일 2009.10.12댓글 1건
    게시물 수정 , 삭제는 로그인 필요

head first java 책에 나와있는 코드 인데요

책에 나온거랑 똑같이 친다음에 실행시켰는데

에러는 안뜨는데 실행이 제대로 안됩니다..

 

 

 

 

 

이건  DotComBust 클래스 코드 이구요

 

import java.util.ArrayList;
public class DotComBust {
 
 private GameHelper helper = new GameHelper();
 private ArrayList dotComsList = new ArrayList();
 private int numOfGuesses = 0;
 
 private void setUpGame()
 {
   DotCom one = new DotCom();
   one.setName("Pets.com");
   DotCom two = new DotCom();
   two.setName("eToys.com");
   DotCom three = new DotCom();
   three.setName("Go2.com");
   dotComsList.add(one);
   dotComsList.add(two);
   dotComsList.add(three);
  
   System.out.println("Yours goal is to sink three dot coms.");
   System.out.println("Pets.com, eToys.com, Go2.com");
   System.out.println("Try to sink them all in the fewest number of guesses");
  
   for(int i=0; i<dotComsList.size(); i++)
   {
    ArrayList newLocation = helper.placeDotCom(3);
    DotCom dotComToSet = (DotCom) dotComsList.get(i);
    dotComToSet.setLocationCells(newLocation); 
   }//for 순환문 끝
  
  }//setupgame 끝
private void startPlaying() {
 while (!dotComsList.isEmpty())
 {
  String userGuess = helper.getUserInput("Enter a guess");
  checkUserGuess(userGuess);
 }
 finishGame();
 
   }

private void checkUserGuess(String userGuess)
{
 numOfGuesses++;
 String result = "miss";
 for (int i = 0; i < dotComsList.size(); i++)
 {
  DotCom dotComToTest = (DotCom) dotComsList.get(i);
  result = dotComToTest.checkYourself(userGuess);
  if(result.equals("hit"))
  {
   break;
  }
  if(result.equals("kill"))
  {
   dotComsList.remove(i);
   break;
  }
 }//for문 끝
}//메소드 끝
private void finishGame(){
 System.out.println("All Dot Coms are dead! Yours stock is now worthless");
 if(numOfGuesses<=18)
 {
  System.out.println("It only took you"+ numOfGuesses + "guesses.");
  System.out.println("You got out before your options sank ");
 } else{
  System.out.println("Took you long enough." + numOfGuesses + "guesses.");
  System.out.println("Fish are dancing with your options.");
 }
 
}//메소드 끝
public static void main (String[] args) {
 DotComBust game = new DotComBust();
 game.setUpGame();
 game.startPlaying();
   }
}

 

 

 

 

 

 

 

이건 닷컴 클래스 입니다


import java.util.*;
public class DotCom {
 private ArrayList locationCells;
 private String name;
 

 public void setLocationCells(ArrayList loc) {
  locationCells = loc;
  
 }
 
 public void setName(String n){
  name = n;
 }
 
 public String checkYourself (String userInput){
  String status = "miss";
  int index = locationCells.indexOf(userInput);
  if (index >= 0) {
   locationCells.remove(index);
   if(locationCells.isEmpty())
     status="kill";
     System.out.println("Ouch! you sunk "+ name +"   :( ");
  }
  else {
   status = "hit";
   
  }
  

 return status;

}//메소드 끝

}//클래스 끝

 

 

 

 

 

 

 

 

 

이건 게임 헬퍼 구요


import java.io.*;
import java.util.*;

public 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("OException: "+e);
  }
  return inputLine.toLowerCase();
 
 }
 
 public ArrayList placeDotCom(int comSize)   //  여기서부터 정말 이해 안되요 ㅠㅠ
 {
  ArrayList alphaCells = new ArrayList();
  String[] alphaCoords = new String [comSize];
  String temp = null;
  int [] coords = new int[comSize];
  int attempts =0;
  boolean success= false;
  int Location = 0;
 
  comCount++;
  int incr = 1;
  if ((comCount % 2)==1)
  {
   incr = gridLength;
  }
 
  while(!success & attempts++ < 200){
   Location = (int) (Math.random()*gridSize);
   //system.out.print("try"+Location);
   int x =0;
   success = true;
   while (success && x < comSize) {
    if(grid[Location]==0)
    {
     coords[x++] =  Location;
     Location += incr;
     if(Location >= gridSize){
      success = false;
     }
     if(x>0 & (Location % gridLength == 0)) {
      success = false;
     }
     
    } else {
     //System.out.print("used"+Location);
     success =  false;
    }
   }
  }
 int x = 0;
 int row = 0;
 int column = 0;
 //System.out.println("\n");
 while (x<comSize)
 {
  grid[coords[x]] = 1;
  row = (int) (coords[x] / gridLength);
  column = coords[x] = 1;
  temp = String.valueOf(alphabet.charAt(column));
 
  alphaCells.add(temp.concat(Integer.toString(row)));
  x++;
 }
 //System.out.println("\n?");
 
 return alphaCells;
 
    }
 }

 

 

 

--------------------------------------------------------------------------------------------

 

이 소스는 닷컴 가라앉히기 게임입니다.

책에 나와있지만...

 

 

대략적으로 설명하면

목표::컴퓨터가 가지고 있는 모든 닷컴명을 가능한 적게 찍어서 모드 가라앉혀야 합니다. 닷컴을 모두 잡고 나면 성적에 따라 등급이 출력됩니다.

 

설정: 게임프로그램이 시작되면 컴퓨터 에서는 닷컴세계를 가장의 7*7그리드위에 배치합니다. 그작업이 끝나면 사용자가 추측한 위치를 입력할 수 있도록 프롬프트를 출력합니다.

 

게임방법: 아직은 GUI 를 만드는 방법을 배우지 않았기 때문에 명령행에서 실행시키는 버전으로 만들겠습니다.

컴퓨터에서는 여러분에게 위치를 찍어보라는 프롬프트를 띄웁니다. 그러면 여러분은 "A3", "C5" 같은 식으로 명령행에 위치를 입력하면 됩니다. 컴퓨터에서는 명령행을 통해 맞으면 "HIT", 틀리면 "MISS" 라고 결과를 알려줍니다. 어떤 닷컴사이트를 모두 적중시켰을때는 "YPU SUNK PETS.COM"같은 메세지를 출력합니다. 닷컴세개를 모두 잡으면 여러분의 등급이 출력됩니다.

 

 

--------------------------------------------------------------------------------------------

제가 궁금한것은 이 게임이 왜 제대로 실행되지 않느냐 하구..

GameHelper 클래스 부분을  주석좀 달아주세요 이해가 잘안되서요.

특히 GameHelpe에 제가 주석달아놓은곳부터는 정말 이해가 잘 안됩니다 ㅜㅜ

coords[]ㅇㅣ게 무슨일 하는지도 모르겠고 ㅜㅜ

 

부탁드립니다.

 

 

 


#자바 코드 #자바 코드 실행 사이트 #자바 코드 컨벤션 #자바 코드 해석 사이트 #자바 코드 정리 #자바 코드 실행 시간 측정 #자바 코드 정렬 #자바 코드 정렬 사이트 #자바 코드 최적화 #자바 코드 예시

profile_image 익명 작성일 -

실행이 안된다는게 정확히 어떻게 안된다는 말인가요?

확실히 실행은 됩니다...

실행은 되는데 원하는대로 움직이지 않는다는 말인가요?

로직을 보면서 이상한부분이 있긴하던데...

이 프로그램이 무엇을 하기위해 만들어졌는지 정확히 알려주지않으셔서(짧게 설명은 있지만)

정확히 프로그램을 이해하진 못했습니다...

 

import java.io.*;
import java.util.*;

public class GameHelper {
 private static final String alphabet = "abcdefg";//위치지정변수
 private int gridLength =7;//위치범위x,y축
 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("OException: "+e);
  }
  return inputLine.toLowerCase();
 
 }
 

//닷컴의 수를 입력받아 배열에 위치정보와 실제위치저장
 public ArrayList placeDotCom(int comSize)   //  여기서부터 정말 이해 안되요 ㅠㅠ
 {
  ArrayList alphaCells = new ArrayList();
  String[] alphaCoords = new String [comSize];
  String temp = null;
  int [] coords = new int[comSize];//실제위치저장배열
  int attempts =0;
  boolean success= false;
  int Location = 0;
 
  comCount++;
  int incr = 1;//위치증가값
  if ((comCount % 2)==1)//홀수번째에 입력된 닷컴이면 incr값을 gridLength로 초기화(특별한 이유는 없는듯)
  {
   incr = gridLength;
  }
 //200번까지 시도하면서 위치정보저장
  while(!success & attempts++ < 200){
   Location = (int) (Math.random()*gridSize);//랜덤하게 구해진 실수값과 gridSize 곱한후 정수값취득
   //system.out.print("try"+Location);
   int x =0;
   success = true;
   while (success && x < comSize) {
    if(grid[Location]==0)//위치정보배열의 Location번째값에 값이 없으면
    {
     coords[x++] =  Location;//위치배열에 Location저장
     Location += incr;//Location에 incr값 플러스
     if(Location >= gridSize){//지정한위치가 지정범위보다크면
      success = false;//위치재설정을위해 success를 false로
     }

//이부분은 정확히 모르겠네요... 홀수번째의 닷컴이면 위치값이 0,7,14등이 되지않도록하고 짝수번째의 닷컴이//면 6,13등이 되지않도록 하기위한것 같은데 정확한 의도는 모르겠습니다... 
     if(x>0 & (Location % gridLength == 0)) {
      success = false;
     }
     //위치정보배열의 Location번째값에 값이 있으면 재설정
    } else {
     //System.out.print("used"+Location);
     success =  false;
    }
   }
  }
 int x = 0;
 int row = 0;
 int column = 0;
 //System.out.println("\n");

//닷컴수만큼 루프
 while (x<comSize)
 {

//위치정보배열의 Location번째의 값을 1로 치환

//위쪽 로직  "if(grid[Location]==0)//위치정보배열의 Location번째값에 값이 없으면"에서 사용, 같은 위치

//의 설정을 막기위해
  grid[coords[x]] = 1;
//7이하는 0, 14이하는 1등으로 row값설정 

row = (int) (coords[x] / gridLength);

//이 부분이 이상하네요...

//위쪽 로직 "private static final String alphabet = "abcdefg";"에서 지정한 abcdefg중의 하나의 값을

//구하기위한 로직인데 1로 치환해 버림으로해서 언제나 abcdefg의 두번째값인 b로설정이 됩니다
//  column =row가 맞을듯...

column = coords[x] = 1;

//abcdefg에서 계산된 column번째의 값을 temp에 저장
  temp = String.valueOf(alphabet.charAt(column));
 //temp에 row를 붙힘 ex)b1,c1등

//temp를 alphaCells에 저장

//사용자가 추측해서 지정한 위치값과 alphaCells값을 비교해서 alphaCells안에 값이 있으면 kill
  alphaCells.add(temp.concat(Integer.toString(row)));
  x++;
 }
 //System.out.println("\n?");
 
 return alphaCells;
 
    }
 }

 

답변이 늦어 졌네요... 연휴보내고 오느라 여기저기 정신이 없어서...

너무 늦진 않았나 모르겟습니다...

혹시 이해안되는 부분있으면 의견이나 쪽지 주세요...

자바 코드 질문 ㅠㅠ

... 메인메소드 작성하시고, 띄우고자 하는 클래스 객체 생성해서 실행해 주는 코드 작성하셔야 합니다.

마인크래프트 자바에디션 실행시 오류

... 오류코드실행이 안되네요 minecraft glfw error 65542 베드락에디션은 잘 작동하는데 자바에디션은 안되는데... 설치법이 궁금하면 1:1 질문하기 이용하세요. 노트북의...

다운받은 자바스크립트 실행이 안되요.

... 이상하게 실행이 되질 않습니다. 다운받은 자바스크... 질문과 같은 코드는 우선 script 태그 안에 있어야만 작용을 하고 호출을 해주어야 실행이 됩니다. 파란...

간단한 자바코드 질문이요.

... 자바가 처음이라 어렵네요 1번째 반복 0 0 일때... if문에서 ++i > 1 && ++j > 1 에 의해서 1 1 이 될 것 처럼... 명령문을 실행합니다 i++; 가 되어 i는 4가 됩니다....

자바 코드 실행오류,,

... System.out.println("삼각형의 넓이:" + t.getArea()); } } 안녕하세요 저번에 답변이 좋아서 다시 질문드려요, 이코드가 아예 실행이안되요...