Kert
Kert

Reputation: 101

while loop conditions java

String userGuessParameters = "a,b";

while (!Character.isDigit(userGuessParameters.charAt(0)) || 
       !Character.isDigit(userGuessParameters.charAt(2)) ||
       userGuessParameters.length() != 3 || 
       (int)(userGuessParameters.charAt(0)) >= parameters[0] || 
       (int)(userGuessParameters.charAt(2)) >= parameters[1]) {

    System.out.print("Mida kaevame (rida, veerg): ");
    userGuessParameters = userInput.nextLine();
    userGuessParameters = userGuessParameters.replaceAll(" ", "");
}

I'm trying to check if all the required conditions are fulfilled in the while loop. parameters is what user entered in array form. Let's assume parameters = [4, 4] (Parameters is used to create a 4x4 map).

I need userGuessParameters to be:

  1. Numbers
  2. Length equal to 3 (the input looks like this: 2,2 when the spaces are removed)
  3. Smaller than the biggest coordinate (which is 3,3)

But for some reason, the loop never exits. I'm almost certain it is because of the last two conditions in the while loop, but I can't find the mistake.

Upvotes: 0

Views: 83

Answers (2)

Abdelhak
Abdelhak

Reputation: 8387

Try to use && instead of || like this:

   while (!Character.isDigit(userGuessParameters.charAt(0)) && !Character.isDigit(userGuessParameters.charAt(2))
       && userGuessParameters.length() != 3 && (int)(userGuessParameters.charAt(0)) >= parameters[0]
       && (int)(userGuessParameters.charAt(2)) >= parameters[1]) {

Upvotes: 1

Idos
Idos

Reputation: 15310

You are using the logical OR operator when you should be using AND (you want all the conditions to be met, not just at least one of them).

Use the java notation for AND which is &&:

(!Character.isDigit(userGuessParameters.charAt(0)) &&
!Character.isDigit(userGuessParameters.charAt(2)) &&
userGuessParameters.length() != 3 &&
(int)(userGuessParameters.charAt(0)) >= parameters[0] &&
(int)(userGuessParameters.charAt(2)) >= parameters[1])

Upvotes: 3

Related Questions