자바 코드 질문 입니다.. 실행이 안되요..
-
게시물 수정 , 삭제는 로그인 필요
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[]ㅇㅣ게 무슨일 하는지도 모르겠고 ㅜㅜ
부탁드립니다.
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[]ㅇㅣ게 무슨일 하는지도 모르겠고 ㅜㅜ
부탁드립니다.
#자바 코드 #자바 코드 실행 사이트 #자바 코드 컨벤션 #자바 코드 해석 사이트 #자바 코드 정리 #자바 코드 실행 시간 측정 #자바 코드 정렬 #자바 코드 정렬 사이트 #자바 코드 최적화 #자바 코드 예시