krabbos krabbos - 3 months ago 8
Java Question

using a method return in java

I am new to java and programming overall, so please bear with me. In the code below,when I run object.ValidateGuess(), I am propted 3 times "Please enter a letter to be guessed:". Why is that? Is it because I use the GetGuess() method in the if statement?? I want to use the return of that method only, not for it to run every time.
thanks in advances

public char GetGuess(){
System.out.println("Please enter a letter to be guessed");
Scanner guess = new Scanner(System.in);
return guess.nextLine().charAt(0);
}

public boolean ValidateGuess(){
boolean isHit = false;
int triesLeft = MAX_TRIES;
if (mCorrectAnswer.indexOf(GetGuess()) < 0 ){
System.out.println("Your guess was incorrect");
triesLeft -= 1;
System.out.println(triesLeft);
mMisses += GetGuess();
} else if (GetGuess() == (int)GetGuess()) {
System.out.println("you have to input a letter!!!");
} else {
mHits += GetGuess();
isHit = true;
}

Answer

In your if conditions you call every time GetGuess so the user has to make an input again and again. You have to save the value from GetGuess and work with that.

(Btw: it is better style to write method names not in capital letters at the beginning).

You can change your code into that:

public char GetGuess(){
    System.out.println("Please enter a letter to be guessed");
    Scanner guess = new Scanner(System.in);
    return guess.nextLine().charAt(0);
}

public boolean ValidateGuess(){
    boolean isHit = false;
    int triesLeft = MAX_TRIES;
    char guessValue = GetGuess(); //Here you store the guess and now you can work with that in your if conditions
    if (mCorrectAnswer.indexOf(guessValue) < 0 ){
        System.out.println("Your guess was incorrect");
        triesLeft -= 1;
        System.out.println(triesLeft);
        mMisses += guessValue;
    } else if (guessValue == (int)guessValue) {
        System.out.println("you have to input a letter!!!");
    } else {
        mHits += guessValue;
        isHit = true;
    }