View Full Version : Help with indexOf() and substring()
01-23-2007, 06:25 PM
I have to make a program that calculates the volume of a circle and then tells me the number of numbers to the left and right of the decimal. I was told to use indexOf and substring to do this. (i.e 23.456 - 2 numbers to the left and 3 to the right). How would i go about doing this? I cannot find a tutorial to show me how to use it in this way.
Firstly, convert the float to a string:
String num = (String)myfloat;Then, use indexOf() to find the position of the decimal point, which is one less than the length of the string before that point:
int placesBefore = num.indexOf((int)('.')) + 1;Finally, take that away from the length of the string to obtain the number of characters after the point:
int placesAfter = num.length() - placesBefore;
01-23-2007, 08:33 PM
I got it working tho not exactly the way you did it. Can u explain to me what indexOf does and why i might of needed substring?
Yes, it's been a while since I did Java, and I've no idea where that +1 came from. It should actually look like:
String num = (new Float(myfloat)).toString();
int placesBefore = num.indexOf((int)'.'),
placesAfter = num.length() - placesBefore - 1;
Can u explain to me what indexOf doesRead the API documentation (http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html) for java.lang.String.
and why i might of needed substring?I'm not entirely sure. It's possible that you were expected to do:
String beforeDecimal = substring(0, placesBefore);
int afterDecimal = substring(placesBefore + 1);
int placesAfter = afterDecimal.length();... but that's a terribly inefficient way of doing it. To accomplish the same effect (but this is still inferior if it's only necessary to find the number of places), one could do:
String decimalSides = num.split("\.");
int beforeDecimal = decimalSides,
afterDecimal = decimalSides;
01-24-2007, 12:10 AM
Ok thanks. But you were kinda of right about the -1. I had to use it on the after.length() - before - 1 because it it counting the decimal and i dont need it to count that.
Argh, yes, of course. I guess I ought to test my code before posting when I haven't slept for a few days :p
02-08-2007, 08:33 PM
ya, indexOf basically counts from the start of a string as 0
where as length starts at one (I belive).
String Hi = "hello"
Hi.length() = 5
hi.subString(1, 2) = "el"
and Hi.indexOf("H") = 0
charAt() might also be a useful function for you it gets the Char at a particular position, but you might want to cast the output to a more handy type other than char
hi.charAt(1) = e
there are also things like
strin.split("."); //which speaks for its self
Powered by vBulletin® Version 4.2.2 Copyright © 2016 vBulletin Solutions, Inc. All rights reserved.