This site requires JavaScript, please enable it in your browser!
Greenfoot back
gusbus123
gusbus123 wrote ...

2012/8/19

String into int.

gusbus123 gusbus123

2012/8/19

#
Is there a way to save a string as an integer? or is it impossible? I have a String that saves what you type and with the code i have it only allows you to type in numbers. Then when i press enter i want it to be saved as a string and pass it through to the world to generate the game with the amount of pins as what the string was saved as. So i have a game generation that rely's on the input of an integer to create the specific amount of pins within the game, and im trying to use the string to input an integer to do the generation of the game.
danpost danpost

2012/8/19

#
What are the range of numbers that are allowed to be input and placed in the string?
danpost danpost

2012/8/19

#
There may be a method to do the conversion for you (like taking the string "1234" and converting it to an int 1234), however the following method will do the job:
private int stringToInteger(String numStr)
{
    int val = 0;
    for (int i = 0; i < numStr.length(); i++) val = val * 10 + "0123456789".indexOf(numStr.charAt(i));
    return val;
}
I think that is what you were looking for. If not, please re-post with specifics. BTW, this will only work as long as all of the characters in the string are numeric.
gusbus123 gusbus123

2012/8/19

#
yer that worked. thx dan
trash1000 trash1000

2012/8/19

#
An easier way would be to use the Integer class of java:
 int formerString = Integer.parseInt(stringInt); 
It's very important that the string only contains numeric characters, otherwise the method will throw an NumberFormatException: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29
You need to login to post a reply.