简体   繁体   中英

Compare Two Strings with Greater than or Lower than Android Studio

i want to compare Two Strings

X = Users Input

Y = System Input

if X is Greater than Y

than show greater than

if X is lower than Y

than show Lower than Here is my code but it is not working

    if (X.compareTo(Y)>-1)  
    {
       Toast.makeText(Activity2.this, "Greater Than", Toast.LENGTH_SHORT).show();
    }
   else {
      Toast.makeText(Activity2.this, "Lower Than", Toast.LENGTH_SHORT).show();
      }

I suppose your > -1 is a clever way of testing for "is equal to or greater than". I suggest avoiding such clever code. Writing stupid-simple code ( KISS ) makes reading and, more to the point here, debugging much easier.

The compareTo method of Comparable interface returns exactly zero if equal. If not equal, the method returns some number greater than zero, or some number less than zero.

To quote the Javadoc:

Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

So change your test to check every single possibility to see how the String#compareTo implementation's behavior does not match your expectations. Make four checks, for equals zero, greater than zero, less than zero, and a fall-through to catch if you ever mistype the first three.

By the way, variable names should start with a lowercase letter, per Java naming conventions. So x , not X .

int comparison = x.compareTo( y ) ;
if ( comparison == 0 )  {
    …
} if ( comparison > 0 )  {
    …
} if ( comparison < 0 )  {
    …
} else { 
    … Oops, the “if” tests must be flawed. We should never reach this point. 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM