Home > database >  Issue with logical operator for Strings
Issue with logical operator for Strings

Time:11-10

I am trying to write a loop to prompt user input until either "AM" or "PM" is entered (case insensitive). However, the following code brings me to an infinite loop even when "AM" or "PM" is being entered. console is my scanner class variable.

String AMPM = "";
do {
    System.out.println("Enter AM or PM: ");
    AMPM = console.next();
} while (!AMPM.equalsIgnoreCase("AM") || !AMPM.equalsIgnoreCase("PM"));

I have tried the to remove the the second ! as such and it only breaks the loop for "AM".

!AMPM.equalsIgnoreCase("AM") || AMPM.equalsIgnoreCase("PM")

What am I doing wrongly?

CodePudding user response:

!AMPM.equalsIgnoreCase("AM") && !AMPM.equalsIgnoreCase("PM")

(as @saka1029deleted suggested) or:

!( AMPM.equalsIgnoreCase("AM") || AMPM.equalsIgnoreCase("PM") )

Explanation

AM PM
!AMPM.equalsIgnoreCase("AM") false true
!AMPM.equalsIgnoreCase("PM") true false
!AMPM.equalsIgnoreCase("AM") && !AMPM.equalsIgnoreCase("PM") false false
AM PM
AMPM.equalsIgnoreCase("AM") true false
AMPM.equalsIgnoreCase("PM") false true
AMPM.equalsIgnoreCase("AM") || AMPM.equalsIgnoreCase("PM") true true
!( AMPM.equalsIgnoreCase("AM") || AMPM.equalsIgnoreCase("PM") ) false false

CodePudding user response:

tl;dr

do { … }
while (
    !
    List
    .of( "AM" , "PM" )
    .contains( input.toUpperCase() )
)

Details

The Answer by hata seems correct.

An alternative approach that I find easier to read involves the use of streams. Make a stream of the target values. Then ask if any of those match your input.

boolean expectedInput = List.of( "AM" , "PM" ).stream().anyMatch( target -> target. equalsIgnoreCase( input ) ) ;

An even simpler alternative asks a list if it contains a copy of the input converted to uppercase.

boolean expectedInput = List.of( "AM" , "PM" ).contains( input.toUpperCase() ) ;
  • Related