В общем решил я все таки дочитать эту дипильную (да да дибильнейшую) Head First Java. Переписал пример под названием "Simple Dot Com" (одно строчный вариант игры). Больше часа не могу заставить ее работать.
Итак, имеем три класса. Первый:
По какому то (мне не известному) стечению обстоятельств условие if (cell == guess) (16 строка) в SimpleDotCom не срабатывает, что приводит к тому что счетчик numberOfHits увеличивается при вводе любого числа. Подскажите люди добрые, а самое главное умные.
public class Main {
public static void main(String[] args) {
int numberOfGuesses = 0;
GameHelper helper = new GameHelper();
SimpleDotCom theDotCom = new SimpleDotCom();
int randomNum = (int) (Math.random() * 5);
System.out.println("random number is " + randomNum);
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);
numberOfGuesses++;
System.out.println("number of guess " + numberOfGuesses);
if (result.equals("kill")) {
isAlive = false;
System.out.println("you took " + numberOfGuesses + " attempts");
}
}
}
}
Второй:
public class SimpleDotCom {
int[] locationCells;
int numberOfHits = 0;
public void setLocationCells(int[] locs) {
locationCells = locs;
}
public String checkYourself(String stringGuess) {
int guess = Integer.parseInt(stringGuess);
String result = "miss";
for (int cell : locationCells) {
if (cell == guess) {
result = "hit";
numberOfHits++;
}
System.out.println("numberOfHits - " + numberOfHits);
numberOfHits++;
break;
}
if (numberOfHits == locationCells.length) {
result = "kill";
}
System.out.println("result - " + result);
return result;
}
}
Третий:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GameHelper {
public String getUserInput(String prompt) {
String inputLine = null;
System.out.println(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("IO" + e.getMessage());
}
return inputLine;
}
}
А вот что происходит в терминале:
