java - string comparing doesn't return right answere -
i want compare 2 strings eachother compareto() function.
example:
int result = "650".compareto("651"); if(result < 0){ system.out.println("smaller"); } else if(result > 0){ system.out.println("bigger"); } else { system.out.println("equals"); } system.out.println(result);
this output smaller correct.
example 2:
int result = "650".compareto("1000"); if(result < 0){ system.out.println("smaller"); } else if(result > 0){ system.out.println("bigger"); } else { system.out.println("equals"); } system.out.println(result);
this return output bigger. kinda strange 650 number smaller 1000.
how's , how can change it? (yes numbers need in text format).
i want this:
int result = "650/65".compareto("1050/50"); if(result < 0){ system.out.println("smaller"); } else if(result > 0){ system.out.println("bigger"); } else { system.out.println("equals"); }
this returns "650/65" bigger "1050/50" yet in fact smaller.
edit
i've worked out cases , how now:
string maat = "650/65"; int submaatb = 0; int submaata = 0; if(maat.contains("/")){ try{ submaata = integer.parseint(maat.substring(0, maat.lastindexof("/"))); submaatb = integer.parseint(maat.substring(maat.lastindexof("/")+1)); } catch (numberformatexception e){ } } boolean resulta = submaata >= 440; boolean resultb = submaatb >= 65; boolean resultc = submaata <= 1050; boolean resultd = submaatb <= 50; if(resulta && resultb && resultc && resultd){ system.out.println("bigger"); } else { system.out.println("smaller"); }
so case is, maat has within range of 440/65 , 1050/50. maat should between range i've mentioned before.
"3".compareto("2")
"three".compareto("two")
meaning both string comparisons.
string.compareto()
compares 2 strings lexicographically. comparison based on unicode value of each character in strings. character sequence represented string object compared lexicographically character sequence represented argument string. result negative integer if string object lexicographically precedes argument string. result positive integer if string object lexicographically follows argument string. result 0 if strings equal; compareto returns 0 when equals(object) method return true.
this definition of lexicographic ordering. if 2 strings different, either have different characters @ index valid index both strings, or lengths different, or both. if have different characters @ 1 or more index positions, let k smallest such index; string character @ position k has smaller value, determined using < operator, lexicographically precedes other string. in case, compareto returns difference of 2 character values @ position k in 2 string -- is, value:
this.charat(k)-anotherstring.charat(k) if there no index position @ differ, shorter string lexicographically precedes longer string. in case, compareto returns difference of lengths of strings -- is, value:
you must convert them integers first if want compare them integers.
Comments
Post a Comment