I'll start by first off saying that my sort must be hard coded. I may not use previously existing sort functions. So i wrote this:
for(int g = 0; g < priceArray.size(); g++)
{
for(int h = 1; h < priceArray.size() - 1; h++)
{
int found = priceArray.get(h).indexOf('$', 8);
if(Double.parseDouble(priceArray.get(h).substring(found+1)) > Double.parseDouble(priceArray.get(h+1).substring(found+1)))
{
String a = priceArray.get(h);
String b = priceArray.get(h+1);
priceArray.set(h,b);
priceArray.set(h+1, a);
}
}
}
Earlier on in the code, this code puts input into the ArrayList:
double oneD = daIS.readDouble();
int twoD = (int)daIS.readDouble();
double threeD = oneD * twoD;
String oneT = (String.format("$%.2f", oneD));
String twoT = (String.format("%s", twoD));
String threeT = (String.format("$%.2f", threeD));
priceArray.add(oneT + " x " + twoT + " = " + threeT);
So basically, this code gets input, puts its into the arraylist, and the sort method then searches for the second $ money sign in the array index, and gets the substring so that it copies the money amount after the $ symbol. Parses it to double and compares it to the next index (h+1).
If index h is larger than index h+1, we switch the two. And the loops keep going. Eventually, in code i didn't post, the code is displayed in a new window in sorted order.
Example: I open program, input 5 and input 3 in spinner. If i press save, these are saved in my binary file and later converted back into the arraylist. I press retrieve and my output is
$5.00 x 3 = $15.00
This works perfectly fine if i input
10 and 5(spinner)
20 and 2
50 and 1
30 and 4
as the output is
$20.00 x 2 = $40.00
$10.00 x 5 = $50.00
$50.00 x 1 = $50.00
$30.00 x 4 = $120.00
but if my input is something like
10 x 1(spinner)
100 x 1
10 x 1
the program breaks and returns
Exception in thread "JavaFX Application Thread"
java.lang.NumberFormatException: For input string: "$100.00"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
I know this is quite confusing and maybe you question the necessity of my hard-coded string sort, but it's a requirement sadly. And works up to a point, so i believe it should be fixable. Thanks for reading.
EDIT: Solution with assistance of @Nabin Bhandari
int found1 = priceArray.get(h).lastIndexOf('$');
int found2 = priceArray.get(h+1).lastIndexOf('$');
if(Double.parseDouble(priceArray.get(h).substring(found1+1)) > Double.parseDouble(priceArray.get(h+1).substring(found2+1)))