Pessoal, estou aprendendo java por meio do livro “Use a Cabeça”, porém o exercício “SimpleDotComGame” não está funcionando como deveria e eu já fucei td e não consigo achar a resposta. Preciso da Ajuda de vocês!!!
public class SimpleDotComGame {
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("insira um numero");
String result = theDotCom.checkYourself(guess);
numOfGuesses++;
if (result == "Kill") {
isAlive = false;
System.out.println("Voce usou " + numOfGuesses + "palpites");
} // encerra if
} // encerra while
} // encerra main
}
import java.io.*;
public 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;
}
}
public 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 cell : locationCells) {
if (guess == cell) {
result = "hit";
numOfHits++;
break;
}
} // fora do loop
if (numOfHits == locationCells.length) {
result = "kill";
}
System.out.println(result);
return result;
} // fecha metodo
} // fecha a classe
Ele compila, porém nunca sai do loop e sempre fica pedindo número, mesmo que apareça “Kill”. E aparece a seguinte mensagem do compilador:
Exception in thread “main” java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at SimpleDotCom.checkYourself(SimpleDotCom.java:12)
at Game.main(Game.java:26)
Ajude-me! Please!!!