mercredi 29 août 2018

Java: How to return the correct value from an int[] array?

I'm new to Java (and programming in general), so apologies if some of this doesn't make sense and/or if the code is really bad:

I am trying get a unique four digit code from a user input (that is what the Keyboard.readInput line does), and I have put in a couple of conditional statements to ensure that the code that is entered can only be 4 digits and that each digit must be different to the other three.

The if statements work as intended in the sense that they output the error message and prompt them to re-enter (i.e. the method getPlayerGuess() gets called). For example, if the user enters 123 (i.e. userGuess.length() != 4), it will prompt them to enter again. If they then enter 1234, the method will complete.

However, the problem I have is that when I call this method in another class that I have, the code that is being pulled through is the first code entered (i.e. 123) and not the four digit one I want (i.e. 1234) - which is resulting in an arrayOutOfBoundsException.

Any ideas on how I can ensure that the code that is being returned is the four digit one that passes the conditionals, and not the first one entered?

public int[] getPlayerGuess() {

System.out.print("Guess a four digit code: ");
String userGuess = Keyboard.readInput();

  if (userGuess.length() != 4) {
      System.out.print("Your code must be 4 digits - ");
      getPlayerGuess();
    }

    int[] userCode = createArrayFromGuess(userGuess);

    for (int i = 0; i < userCode.length-1; i++){
        for (int j = i+1; j < userCode.length; j++){
            if (userCode[i] == userCode[j]) {
                System.out.print("Code must have four unique digits - ");
                getPlayerGuess();
            }
        }
    }
    return userCode;
}

Aucun commentaire:

Enregistrer un commentaire