Monday, October 25, 2010

J2ME tips

Here are some tips/ tricks for the very simple problems

Float in CLDC1.0 :
This is the method i wrote years ago when needed to work in CLDC 1.0 with Float. As you might be aware that Float is not supported in CLDC1.0 so it compares the 2 float values given it as String. I have not revised the code so there would be a lot of room to optimize it

public static boolean compareFloats(String str1, String str2)
{
final char DECIMAL = '.';
int decimal = (int) DECIMAL;
str1 = str1.trim();
str2 = str2.trim();
int firstDecimalPosition = str1.indexOf(decimal);
int secondDecimalPosition = str2.indexOf(decimal);

if (firstDecimalPosition == -1)
{
str1 = str1.concat(".0");
firstDecimalPosition = str1.indexOf(decimal);
}
if (secondDecimalPosition == -1)
{
str2 = str2.concat(".0");
secondDecimalPosition = str2.indexOf(decimal);
}

if (str1.substring(0, firstDecimalPosition).equals("0") &&
str2.substring(0, secondDecimalPosition).equals("-0"))
{

return true;
}

if (str1.substring(0, firstDecimalPosition).equals("-0") &&
str2.substring(0, secondDecimalPosition).equals("0"))
{

return false;
}

int firstValue = Integer.parseInt(str1.substring(0,
firstDecimalPosition));
int secondValue = Integer.parseInt(str2.substring(0,
secondDecimalPosition));

if (firstValue > secondValue)
{

return true;
}
else if (firstValue <>
{
return false;

}
else
{
String firstValAfterDec = str1.substring(firstDecimalPosition + 1,
str1.length()).trim();
String secondValAfterDec = str2.substring(secondDecimalPosition + 1,
str2.length()).trim();
int length1 = firstValAfterDec.length();
int length2 = secondValAfterDec.length();
int difference;
if (firstValAfterDec.length() <>
{
difference = length2 - length1;
for (int i = 0; i <>
{
firstValAfterDec = firstValAfterDec + "0";
}
}
if (secondValAfterDec.length() <>
{
difference = length1 - length2;
for (int i = 0; i <>
{
secondValAfterDec = secondValAfterDec + "0";
}
}

firstValue = Integer.parseInt(firstValAfterDec);
secondValue = Integer.parseInt(secondValAfterDec);

if (firstValue > secondValue)
{

return true;
}
else if (firstValue <>
{
return false;

}
else
/** if both value are equal return false*/
{

return false;

}

}

}


equalIqnoreCase in CLDC 1.0:

Again fairly simple

public static boolean equalStrings(String first, String second)
{
first = first.trim().toLowerCase();
second = second.trim().toLowerCase();
return first.equals(second);
}


No comments:

Post a Comment