dcsimg
compareTo with numeric strings not working as expected
3 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Hagamoto_Yamocho
Posted On:   Tuesday, June 11, 2002 05:58 AM

Running this code

			
String str1 = "1";
String str2 = "2";
int compareVal = str1.compareTo(str2);


always returns zero. Setting str1 to "1" and str2 to "a" also always returns zero. I would like the comparison to return -1 in both cases. What am I missing here?

Thanks in advance for any help.

Re: compareTo with numeric strings not working as expected

Posted By:   Sean_Ruff  
Posted On:   Tuesday, June 11, 2002 06:25 AM

Not questioning you but I checked it and it worked fine for me. Please make sure the you are not missing something simple like checking the wrong variable or reseting that variable and remember it is comparing them according to their Unicode value. Trying running this:


public class TestCompareTo {

public static void main(String[] args){
String str1 = "1";
String str2 = "2";
System.out.println(str1.compareTo(str2));

}
}



Hope you figure it out.

Re: compareTo with numeric strings not working as expected

Posted By:   Anonymous  
Posted On:   Tuesday, June 11, 2002 06:21 AM

This code returns -1 (JDK 1.2.2)...

Re: compareTo with numeric strings not working as expected

Posted By:   Simon_Ablett  
Posted On:   Tuesday, June 11, 2002 06:13 AM

Your example code returns '-1' for me using jdk1.3.1 (as expected). My test code is as follows.


import java.io.*;

public class tt
{
public static void main( String [] args )
{
String str1 = "1";
String str2 = "2";
int compareVal = str1.compareTo(str2);
System.out.println("Value=("+compareVal+")");
}
}

Changing the value of 'str2' to 'a' returns '-48' and changing it to '1' returns '0'. All as expected. I think that you may have some other problem with your code.

Regards.
About | Sitemap | Contact