NoobException
NoobException

Reputation: 666

java compareTo not working with double digit numbers

The following code works correctly if I use 0 or 9 for menuInput, the loop iterates again. if I use 10, the loop condition is satisfied and it exits. I guess compareTo only seems the first value when I use it this way? When I made menuInput 99, the loop iterates again. I'm a beginner and I'm not sure what to replace compareTo with. TY!

do...

code

while (menuInput.compareTo("8") > 0 || menuInput.compareTo("1")<0);

Upvotes: 1

Views: 825

Answers (2)

selig
selig

Reputation: 4844

compareTo in String is lexicographical - it orders alphabetically by the first character and then the next so "1" < "2" but "11" < "2" also. If you want to do numeric comparison then convert to an integer using Integer.parseInt.

Upvotes: 11

rob
rob

Reputation: 6247

You're comparing Strings. If you wish to compare the numeric values, you will need to convert them to Integers.

Upvotes: 0

Related Questions