I'm a java beginner and I'm reading First head Java book. I did manage what the book asks for, but I'm trying to improve the program
the program is supposed to generate a random number between 0-7, then put it an an array with the following two number and the user has to guess it. everything is working except that I'm trying to restrict the user from entering anything but numbers from 0 to 7
here is my try, and I don't know why it's not working:
public String checkYourSelf (String stringGuess){
String result = "miss"; //this will be returned if the guess doesn't match
if (stringGuess != "0" ||
stringGuess != "1" ||
stringGuess != "2" ||
stringGuess != "3" ||
stringGuess != "4" ||
stringGuess != "5" ||
stringGuess != "6" ||
stringGuess != "7" ){
System.out.println("Please Enter a correct number");
result = "error";
return result;
}
and after this I use the parseInt method
int guess = Integer.parseInt(stringGuess);
the whole method :
public String checkYourSelf (String stringGuess){
String result = "miss"; // this will be returned if the guess doesn't match
if (stringGuess != "0" ||
stringGuess != "1" ||
stringGuess != "2" ||
stringGuess != "3" ||
stringGuess != "4" ||
stringGuess != "5" ||
stringGuess != "6" ||
stringGuess != "7" ){
System.out.println("Please Enter a correct number");
result = "error";
return result;
}
int guess = Integer.parseInt(stringGuess);
for (int cell : cellsLocations) {
if (enterdNums.contains(guess)){
result = "error";
System.out.println ("You've entered this number already.");
System.out.println("Please try again");
break;
}
if (cell == guess) {
result = "hit";
hits++;
break;
}
}
if (hits == cellsLocations.length) {
result = "kill";
}
if (result != "error"){
System.out.println(result);
}
enterdNums.add(guess); // add to the list so it doesnt
return result;
}
}
in the main method :
while (isAlive) {
guess = input.getUserInput("Enter a number");
result = dot.checkYourSelf(guess);
if (result == "error"){
continue;
}
numOfGuesses++;
if (result == "kill"){
System.out.println(numOfGuesses);
isAlive = false;
break;
}
}
I know there might be other ways to do this, but I'm trying to do it from stuff I know already, and logically this should be working, however if I enter any number it will say "Please enter a correct number"
thanks