Parsing from string to int

in my C# project I have an array type of String. the array gets numbers from type int.
int numCell;
string[] arr = new string[numCell];
then i use it in a function like this:
sum += int.Parse(arr[i]);
and it works!
but, when i dothe same thing in WPF it tells me:
Input string was not in a correct format.
what shouuld i do?

Why did you mark your own question as answer? Please unmark it.
>>if in C# it worked why wouldn't it work in wpf?
As I have already mentioned, it is because of the actual value of arr[i]. It has nothing to do with Windows Forms or WPF but it is possible that your WPF application has put a different value in the array than your Windows Forms Application did. And if this
specific value is not a valid number the parsing will always fail. So you should check the values that put into the array and probably use the int.TryParse method to do the parsing:
int sum;
if (!int.TryParse(arr[i], out sum))
//the value of arr[i] was NOT a valid number...
This will however not change the fact that for example the value "D1" cannot be converted to an int using the int.Parse or int.TryParse method.
Please remember to close your threads by marking helpful posts as answer and please start a new thread if you have a new question.

Similar Messages

  • Convert from String to Int

    Hi,
    I have a question.
    How do I convert from String to Integer?
    Here is my code:
    try{
    String s="000111010101001101101010";
    int q=Integer.parseInt(s);
    answerStr = String.valueOf(q);
    catch (NumberFormatException e)
    answerStr="Error";
    but, everytime when i run the code, i always get the ERROR.
    is the value that i got, cannot be converted to int?
    i've done the same thing in c, and its working fine.
    thanks..

    6kyAngel wrote:
    actually it convert the string value into decimal value.In fact what it does is convert the (binary) string into an integer value. It's the String representation of integer quantities that have a base (two, ten, hex etc): the quantities themselves don't have a base.
    To take an integer quantity (in the form of an int) and convert it to a binary String, use the handy toString() method in the Integer class - like your other conversion, use the one that takes a radix argument.

  • Parsing formatted String to Int

    How can I parse formatted string to Integer ?
    I have a formated string like this $900,000 and I need to convert it to 900000 so I could do calculations with it.
    I tried something like this
    NumberFormat nf = NumberFormat.getIntegerInstance(request.getLocale());
    ttlMargin=nf.parse(screenVal);I got this exception
    "java.lang.NumberFormatException: For input string: "$1,050,000""

    I am working on the JSP file that provides
    margins,sales etc. I am reading this data off the
    screen where it is beeing displayed according to the
    accounting practices.
    That's why I get it as a formatted string and why I
    am trying covert that string to the numberScreen-scraping is a problematic, bad design. It sounds like what you really want is to call a web service which returns its results as data that a program can understand (XML, for example), not HTML (which is meant more for humans to read). I know, you probably can't change the design at this point... just food for thought. In the meantime, you'll probably have to manually parse those strings yourself by stripping out the '$' and ',' characters and then use parseInt on the result.

  • Please help me with my code (has conversion from string to int)

    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    public class Test3 extends MIDlet implements CommandListener
    {   Form mForm;
        Command mCommandQuit;
        Command mCommandItem;
        TextField input,prime1,prime2,prime3,output;
        Display mDisplay;
        int i,j=0,k1,k2,p,q,b;
        //int [] current=new int [1000];
        String mstring,a="";
        String [] temp=new String [1000];
        public void startApp()
        {System.out.println("startApp");
         mForm=new Form("RSA Encryption");
         mCommandQuit=new Command("QUIT",Command.EXIT,0);
         mCommandItem=new Command("ENCRYPT",Command.ITEM,0);
         mForm.append("Enter text:\n");
         input=new TextField(null,"",100, TextField.ANY);
         mForm.append(input);
         mForm.append("Enter first prime number(p):\n");
         prime1=new TextField(null,"",100, TextField.ANY);
         mForm.append(prime1);
         mForm.append("Enter second prime number(q):\n");
         prime2=new TextField(null,"",100, TextField.ANY);
         mForm.append(prime2);
         mForm.append("Enter d:\n");
         prime3=new TextField(null,"",100, TextField.ANY);
         mForm.append(prime3);
         mForm.addCommand(mCommandQuit);
         mForm.addCommand(mCommandItem);
         mDisplay=Display.getDisplay(this);
         mDisplay.setCurrent(mForm);
         mForm.setCommandListener(this);
        public void pauseApp()
        {System.out.println("pauseApp");
        public void destroyApp(boolean unconditional)
        {System.out.println("destroyApp");
        public void commandAction(Command c, Displayable d)
        {System.out.println("commandAction");
         if(c==mCommandQuit)
            notifyDestroyed();
         else if(c==mCommandItem)
         {p = Integer.parseInt(prime1.getString());
             q = Integer.parseInt(prime2.getString());
             b = Integer.parseInt(prime3.getString());
             //breaking up of big string into ints
             mstring=input.getString();
             temp[0]="";
             for(i=1;i<mstring.length();i++)
                {if (mstring.charAt(i) == ' ')
                    {j++;
                     temp[j]="";
                 else
                    {temp[j]=temp[j]+mstring.charAt(i);
             mForm.append("\n\nThe array is:\n");
             for(i=0;i<temp.length && temp!=null;i++)
    {k1=Integer.parseInt(temp[i]); ***********************
    k2=k1;
    for(j=1;j<b;j++)
    {k1=k1*k2;
    k1=k1 %(p*q);
    k2=k1 %(p*q);
    a=a+new Character((char)k2).toString();
    output=new TextField(null,a,100, TextField.ANY);
    mForm.append(output);
    }hi
    this code basically takes an input of string like " 179 84 48 48 155 " (with spaces)
    then it creates smaller strings in an array like "179","84","48","48","155" without the spaces
    then it creates int values 179,84,48,48,155 and finally after some math functions it prints the corresponding letters.
    the problem is that it is not printing the letter because of some exceptions-->java.lang.NumberFormatException .it comes in the line where i have put stars
    could anybody please help me print the letters                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    thanks for all ur help guys, but me and my team member solved it on our own. here is the new code:
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    public class Test3 extends MIDlet implements CommandListener
    {   Form mForm;
        Command mCommandQuit;
        Command mCommandItem;
        TextField input,prime1,prime2,prime3,output;
        Display mDisplay;
        int i,j=0,l,k1,k2,p,q,n,b;
        String mstring,a = "";
        String [] temp=new String [1000];
        public void startApp()
        {System.out.println("startApp");
         mForm=new Form("RSA Encryption");
         mCommandQuit=new Command("QUIT",Command.EXIT,0);
         mCommandItem=new Command("DECRYPT",Command.ITEM,0);
         mForm.append("Enter text:\n");
         input=new TextField(null,"",100, TextField.ANY);
         mForm.append(input);
         mForm.append("Enter first prime number(p):\n");
         prime1=new TextField(null,"",100, TextField.NUMERIC);
         mForm.append(prime1);
         mForm.append("Enter second prime number(q):\n");
         prime2=new TextField(null,"",100, TextField.NUMERIC);
         mForm.append(prime2);
         mForm.append("Enter d:\n");
         prime3=new TextField(null,"",100, TextField.NUMERIC);
         mForm.append(prime3);
         mForm.addCommand(mCommandQuit);
         mForm.addCommand(mCommandItem);
         mDisplay=Display.getDisplay(this);
         mDisplay.setCurrent(mForm);
         mForm.setCommandListener(this);
        public void pauseApp()
        {System.out.println("pauseApp");
        public void destroyApp(boolean unconditional)
        {System.out.println("destroyApp");
        public void commandAction(Command c, Displayable d)
        {System.out.println("commandAction");
         if(c==mCommandQuit)
            notifyDestroyed();
         else if(c==mCommandItem)
         {p = Integer.parseInt(prime1.getString());
             q = Integer.parseInt(prime2.getString());
             b = Integer.parseInt(prime3.getString());
             n=p*q;
             //breaking up of big string into ints
             mstring=input.getString();
             temp[0]="";
             for(i=1;i<mstring.length();i++)
                {if (mstring.charAt(i) == ' ')
                    {j++;
                     temp[j]="";
                 else
                    {temp[j]=temp[j]+mstring.charAt(i);
             l=j;
             mForm.append("\n\nThe result is:\n");
             for(i=0;i<l;i++)
                {k1=Integer.valueOf(temp).intValue();
    k2=k1;
    for(j=1;j<b;j++)
    {k2=k2*k1;
    k2=k2 %n;
    k1=k2 %n;
    a=a+new Character((char)k1).toString();
    output=new TextField(null,a,100, TextField.ANY);
    mForm.append(output);

  • Leading Zeroes are lost when convert from string to int

    What I'm trying to do is simple yet the solution has seemed difficult to find.
    I have a system that requires 4 digit numbers as "requisitionNo". The system uses JSPs and accepts the 4 digit number that the user inputs (fyi - duplicate handling is already managed). The input number (rNumber) is of STRING type and in the action (using struts) is converted to an int:
    int requisitionNo = Integer.parseInt(rNumber);At that very line the issue is that when the user inputs a number with leading zeros such as: "0001" the 3 leading zeros are chopped off in the INT conversion. The application validation kicks in and says: "A 4 digit number is required" which is by design. The work around has been that the user has been putting in number that start with 9's or something like that, but this isn't how the system was intended to be used.
    How do I keep the leading zeroes from being lost instead of saving a number "1" to the database how do I keep it saving "0001" to the database? Would I just change everything to STRING on down to the database? or is there another number type that I can be using that will not chop off the leading zeroes? Please provide short code references or examples to be more helpful.

    Yeah, I have to agree here that leading zeroes make no sense. I figured that out when I started to look into this problem. The only requirement that exists is that the user wants it to be a 4 digit number due to some other requirement they have themselves.
    So what I'm gathering from what I've read in the responses thus far is that I should change the validation a bit to look at the STRING for the 4 required digits (which are really 4 characters; maybe I should add CLIENT side numeric validation; currently its doing server side numeric/integer validation; or maybe change up the server side validation instead???) and if they are ALL GOOD then let the application save the int type as it wants to. IE: Let it save "0001" as just "1" and when I come back to DISPLAY this saved number to the user I should append the string of "000" in front of the 1 for display purposes only? Am I understanding everyone correctly?

  • Parsing from string to date object

    How can I convert a time in String format to a Date object?
    ie. 14:30:05(String) to 14:30:05

    How about this?
    String sDate = "14:30:05";
    StringTokenizer tokenizer = new StringTokenizer(sDate, ":");
    Calendar calendar = new Calendar();
    int hour = Integer.parseInt(tokenizer.nextToken());
    int minute = Integer.parseInt(tokenizer.nextToken());
    int second = Integer.parseInt(tokenizer.nextToken());
    calendar.set(Calendar.HOUR_OF_DAY, int hour);
    calendar.set(Calendar.MINUTE, int minute);
    calendar.set(Calendar.SECOND, int second);
    Date dDate = calendar.getTime();I didn't try it, but it should be pretty close (unless you want to use deprecated methods, then it can be shorter...)

  • Conversion from String to int..NumberFormatException??

    Hey all
    I am trying to read in a file that has nothing but numbers listed one per line. I am using the bufferedReader class and reading in by line. When I check to see if the one 'string' is the same as another, it says they are the same, when really they are different. I then thought to convert the numbers to integers after reading them in, but it gives me a number format exception. My process is simple:
    1) line = in.readLine();
    2) int variable = Integer.valueOf(line).intValue();
    This gives me the damn exception. The numbers are three digits, e.g. 333, etc. Does anybody know how I can avert this problem or achieve the result I am looking for another way? All I want is to know what numbers are listed in their, without going through by hand checking. Thanks

    hi...try this..
    1.Use filereader instead of bufferedreader..OKAY
    2. OR USE...
    String str = br.readLine();
    use... int sanjeev = Integer.parseInt(str);
    3 OR...and helloooo one thing more...how u r checking that these 2 strings r same..
    get CLEAR IDEA about equals method and "=="..

  • Conversion from String to Int

    import java.io.*;
    import java.util.*;
    import java.lang.*;
    public static void main(String[] args) throws Exception{
    int Ze=0;
    String Temp = "512";
    Ze = parseInt(Temp);
    I got an error saying --->>
    cannot resolve symbol
    symbol : method parseInt(java.lang.String)
    I tried using ...Integer(Temp)
    and it gives me a similar error message.
    where Did i went wrong???

    http://java.sun.com/j2se/1.5.0/docs/api/index.html
    Bookmark that page. It's the index to the documentation of every class in Java 1.5.0. If you've got a different JDK, look on the download page and find the Documentation. Look for the API documentation in that.
    Go look up the Byte class and see. The API documentation tells every available method for every available class in the java.*, javax.*, and org.* packages. Better start getting used to using it now rather than later.

  • Reading Hex data- how to typecast from string

    Hi,
    I am reading a file having hex data ( say 100 lines).When i read it i think it is being read as a string.
    How can i typecast or convert it to int .
    I am using dis.readLine() to read from file and assigning it to a variable(int).
    Thanks.
    Edited by: Motorcycle on Jun 10, 2009 3:16 PM

    Sorry for that..:)
    ok a few lines of the file are as folloes
    0x004D1202
    0x0002E1E5
    0x004C1202
    0x0002E1EB
    0x004E1202
    I tried reading it as data [indr][indc].tag = ( int ) dis.readLine() ;
    It said " cannot convert from String to int.
    data is a structure having int variables.
    Thanks.

  • Passing / parsing XML String IN / OUT from PL / SQL package

    Hello, People !
    I am wondering where can I find exact info (with code sample) about following :
    We use Oracle 8.1.6 and 8.1.7. I need to pass an XML String (could be from VARCHAR2 to CLOB) from VB 6.0 to PL/SQL package. Then I need to use built in PL/SQL XML parser to parse given string (could be large hierarchy of nodes)
    and the return some kind of cursor thru I can loop and insert data into
    different db Tables. (The return value may have complex parent/child data relationship - so I am not sure If this should be a cursor)
    I looked online many site for related info - can't find what I am looking
    for - seems like should be a common question.
    Thanx a lot !

    Hello, People !
    I am wondering where can I find exact info (with code sample) about following :
    We use Oracle 8.1.6 and 8.1.7. I need to pass an XML String (could be from VARCHAR2 to CLOB) from VB 6.0 to PL/SQL package. Then I need to use built in PL/SQL XML parser to parse given string (could be large hierarchy of nodes)
    and the return some kind of cursor thru I can loop and insert data into
    different db Tables. (The return value may have complex parent/child data relationship - so I am not sure If this should be a cursor)
    I looked online many site for related info - can't find what I am looking
    for - seems like should be a common question.
    Thanx a lot !

  • Parse/seperate data from string

    I have a string that is returned from Google GeoCoding:
    {   "name": "193 Farrow Hill Road,Davisville,WV",   "Status": {     "code": 200,     "request": "geocode"   },   "Placemark": [ {     "id": "p1",     "address": "Davisville, WV, USA",     "AddressDetails": {    "Accuracy" : 4,    "Country" : {       "AdministrativeArea" : {          "AdministrativeAreaName" : "WV",          "SubAdministrativeArea" : {             "Locality" : {                "LocalityName" : "Davisville"             },             "SubAdministrativeAreaName" : "Wood"          }       },       "CountryName" : "USA",       "CountryNameCode" : "US"    } },     "ExtendedData": {       "LatLonBox": {         "north": 39.2357655,         "south": 39.1665921,         "east": -81.4344257,         "west": -81.5624851       }     },     "Point": {       "coordinates": [ -81.4984554, 39.2011873, 0 ]     }   } ] }
    I want to be able to parse this data into variables that I can use and update a table.
    I currently use ListGetAt() function and try to find common delimiters to narrow down what I am trying to parse, but this processes does not always return the results I am needing.
    Does anyone know of any faster more robust way of parsing this string down to variables? And, it could be that I am not using the ListGetAt() to its full potential as well....
    What I need most out of this string is in bold below...you'll notice different string lengths depending on if it recognizes the street address or not.
    This is the string returned if it DOES NOT recognize the street address:
    {   "name": "193 Farrow Hill Road,Davisville,WV",   "Status": {     "code": 200,     "request": "geocode"   },   "Placemark": [ {     "id": "p1",     "address": "Davisville, WV, USA",     "AddressDetails": {    "Accuracy" : 4,    "Country" : {       "AdministrativeArea" : {          "AdministrativeAreaName" : "WV",          "SubAdministrativeArea" : {             "Locality" : {                "LocalityName" : "Davisville"             },             "SubAdministrativeAreaName" : "Wood"          }       },       "CountryName" : "USA",       "CountryNameCode" : "US"    } },     "ExtendedData": {       "LatLonBox": {         "north": 39.2357655,         "south": 39.1665921,         "east": -81.4344257,         "west": -81.5624851       }     },     "Point": {       "coordinates": [ -81.4984554, 39.2011873, 0 ]     }   } ] }
    This is the string returned if it DOES recognize the street address:
    {   "name": "W7499 So. Mound Rd,Neillsville,WI",   "Status": {     "code": 200,     "request": "geocode"   },   "Placemark": [ {     "id": "p1",     "address": "S Mound Rd, Neillsville, WI 54456, USA",     "AddressDetails": {    "Accuracy" : 6,    "Country" : {       "AdministrativeArea" : {          "AdministrativeAreaName" : "WI",          "SubAdministrativeArea" : {             "Locality" : {                "LocalityName" : "Neillsville",                "PostalCode" : {                   "PostalCodeNumber" : "54456"                },                "Thoroughfare" : {                   "ThoroughfareName" : "S Mound Rd"                }             },             "SubAdministrativeAreaName" : "Clark"          }       },       "CountryName" : "USA",       "CountryNameCode" : "US"    } },     "ExtendedData": {       "LatLonBox": {         "north": 44.5921279,         "south": 44.5858326,         "east": -90.5981846,         "west": -90.6802503       }     },     "Point": {       "coordinates": [ -90.6394276, 44.5889072, 0 ]     }   }, {     "id": "p2",     "address": "S Mound Rd, Neillsville, WI 54456, USA",     "AddressDetails": {    "Accuracy" : 6,    "Country" : {       "AdministrativeArea" : {          "AdministrativeAreaName" : "WI",          "SubAdministrativeArea" : {             "Locality" : {                "LocalityName" : "Neillsville",                "PostalCode" : {                   "PostalCodeNumber" : "54456"                },                "Thoroughfare" : {                   "ThoroughfareName" : "S Mound Rd"                }             },             "SubAdministrativeAreaName" : "Clark"          }       },       "CountryName" : "USA",       "CountryNameCode" : "US"    } },     "ExtendedData": {       "LatLonBox": {         "north": 44.5920678,         "south": 44.5857725,         "east": -90.6802503,         "west": -90.7004168       }     },     "Point": {       "coordinates": [ -90.6899796, 44.5889209, 0 ]     }   } ] }

    That is indeed JSON, as Jochem says. You can pick out data using structs and arrays. You will know which structure or array functionality to use after doing something like this
    <cfsavecontent variable="myJSON1">
    {   "name": "193 Farrow Hill Road,Davisville,WV",   "Status": {     "code": 200,     "request": "geocode"   },   "Placemark": [ {     "id": "p1",     "address": "Davisville, WV, USA",     "AddressDetails": {    "Accuracy" : 4,    "Country" : {       "AdministrativeArea" : {          "AdministrativeAreaName" : "WV",          "SubAdministrativeArea" : {             "Locality" : {                "LocalityName" : "Davisville"             },             "SubAdministrativeAreaName" : "Wood"          }       },       "CountryName" : "USA",       "CountryNameCode" : "US"    } },     "ExtendedData": {       "LatLonBox": {         "north": 39.2357655,         "south": 39.1665921,         "east": -81.4344257,         "west": -81.5624851       }     },     "Point": {       "coordinates": [ -81.4984554, 39.2011873, 0 ]     }   } ] }
    </cfsavecontent>
    <cfsavecontent variable="myJSON2">
    {   "name": "W7499 So. Mound Rd,Neillsville,WI",   "Status": {     "code": 200,     "request": "geocode"   },   "Placemark": [ {     "id": "p1",     "address": "S Mound Rd, Neillsville, WI 54456, USA",     "AddressDetails": {    "Accuracy" : 6,    "Country" : {       "AdministrativeArea" : {          "AdministrativeAreaName" : "WI",          "SubAdministrativeArea" : {             "Locality" : {                "LocalityName" : "Neillsville",                "PostalCode" : {                   "PostalCodeNumber" : "54456"                },                "Thoroughfare" : {                   "ThoroughfareName" : "S Mound Rd"                }             },             "SubAdministrativeAreaName" : "Clark"          }       },       "CountryName" : "USA",       "CountryNameCode" : "US"    } },     "ExtendedData": {       "LatLonBox": {         "north": 44.5921279,         "south": 44.5858326,         "east": -90.5981846,         "west": -90.6802503       }     },     "Point": {       "coordinates": [ -90.6394276, 44.5889072, 0 ]     }   }, {     "id": "p2",     "address": "S Mound Rd, Neillsville, WI 54456, USA",     "AddressDetails": {    "Accuracy" : 6,    "Country" : {       "AdministrativeArea" : {          "AdministrativeAreaName" : "WI",          "SubAdministrativeArea" : {             "Locality" : {                "LocalityName" : "Neillsville",                "PostalCode" : {                   "PostalCodeNumber" : "54456"                },                "Thoroughfare" : {                   "ThoroughfareName" : "S Mound Rd"                }             },             "SubAdministrativeAreaName" : "Clark"          }       },       "CountryName" : "USA",       "CountryNameCode" : "US"    } },     "ExtendedData": {       "LatLonBox": {         "north": 44.5920678,         "south": 44.5857725,         "east": -90.6802503,         "west": -90.7004168       }     },     "Point": {       "coordinates": [ -90.6899796, 44.5889209, 0 ]     }   } ] }
    </cfsavecontent>
    <cfdump var="#deserializeJSON(myJSON1)#">
    <cfdump var="#deserializeJSON(myJSON2)#">

  • Parsing from a string of XML?

    Hi there,
    I'm using DOM to parse some XML. However, the XML is not in a file, it's in a String. So the DocumentBuilder's parse(...) method takes an InputStream or File object but I'm looking to parse a String. Can anybody help me??
    Cheers,
    Sean

    Ok I found out a way to parse an XML string:
    DocumentBuilder builder = factory.newDocumentBuilder();
    StringReader sr = new StringReader(xmlString.toString());
    InputSource is = new InputSource(sr);
    document = builder.parse(is);
    But I'm getting the following error on the parse() line:
    [Fatal Error] :1:20: A pseudo attribute name is expected.
    org.xml.sax.SAXParseException: A pseudo attribute name is expected.
         at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
         at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
         at test.TestDOM.main(TestDOM.java:61)
    The XML string is:
    String xmlString = "<?xml version=\"1.0\"><tag><tag_id>250397</tag_id><reader_id>1</reader_id><rssi>74</rssi><date>7/19/2006</date><time>2:59:47 PM</time></tag>";
    Can anybody help?
    Cheers,
    Sean

  • How to parse a string in CVP 7.0(1). Is there a built-in java class, other?

    Hi,
    I need to parse,in CVP 7.0(1), the BAAccountNumber variable passed by the ICM dialer.  Is there a built-in java class or other function that would help me do this?
    Our BAAccountNumber variable looks something like this: 321|XXX12345678|1901|M. In IP IVR I use the "Get ICM Data" object to read the BAAccountNumber variable from ICM and then I use the "token index" feature to parse the variable (picture below).
    Alternately, IP IVR also has a Java class that allows me to do this; the class is "java.lang.String" and the method is "public int indexOf(String,int)"
    Is there something equivalent in CVP 7.0(1)?
    thanks

    Thanks again for your help.  This is what I ended up doing:
    This configurable action element takes a string seperated by two "|" (123|123456789|12)
    and returns 3 string variables.
    you can add more output variables by adding to the Setting array below.
    // These classes are used by custom configurable elements.
    import com.audium.server.session.ActionElementData;
    import com.audium.server.voiceElement.ActionElementBase;
    import com.audium.server.voiceElement.ElementData;
    import com.audium.server.voiceElement.ElementException;
    import com.audium.server.voiceElement.ElementInterface;
    import com.audium.server.voiceElement.Setting;
    import com.audium.server.xml.ActionElementConfig;
    public class SOMENAMEHERE extends ActionElementBase implements ElementInterface
         * This method is run when the action is visited. From the ActionElementData
         * object, the configuration can be obtained.
        public void doAction(String name, ActionElementData actionData) throws ElementException
            try {
                // Get the configuration
                ActionElementConfig config = actionData.getActionElementConfig();
                //now retrieve each setting value using its 'real' name as defined in the getSettings method above
                //each setting is returned as a String type, but can be converted.
                String input = config.getSettingValue("input",actionData);
                String resultType = config.getSettingValue("resultType",actionData);
                String resultEntityID = config.getSettingValue("resultEntityID",actionData);
                String resultMemberID = config.getSettingValue("resultMemberID",actionData);
                String resultTFNType = config.getSettingValue("resultTFNType",actionData);
                //get the substring
                //String sub = input.substring(startPos,startPos+numChars);
                String[] BAAcctresults = input.split("\\|");
                //Now store the substring into either Element or Session data as requested
                //and store it into the variable name requested by the Studio developer
                if(resultType.equals("Element")){
                    actionData.setElementData(resultEntityID,BAAcctresults[0]);
                    actionData.setElementData(resultMemberID,BAAcctresults[1]);
                    actionData.setElementData(resultTFNType,BAAcctresults[2]);
                } else {
                    actionData.setSessionData(resultEntityID,BAAcctresults[0]);
                    actionData.setSessionData(resultMemberID,BAAcctresults[1]);
                    actionData.setSessionData(resultTFNType,BAAcctresults[2]);
                actionData.setElementData("status","success");
            } catch (Exception e) {
                //If anything goes wrong, create Element data 'status' with the value 'failure'
                //and return an empty string into the variable requested by the caller
                e.printStackTrace();
                actionData.setElementData("status","failure");
        public String getElementName()
            return "MEDDOC PARSER";
        public String getDisplayFolderName()
            return "SSC Custom";
        public String getDescription()
            return "This class breaks down the BAAccountNumber";
        public Setting[] getSettings() throws ElementException
             //You must define the number of settings here
             Setting[] settingArray = new Setting[5];
              //each setting must specify: real name, display name, description,
              //is it required?, can it only appear once?, does it allow substitution?,
              //and the type of entry allowed
            settingArray[0] = new Setting("input", "Original String",
                       "This is the string from which to grab a substring.",
                       true,   // It is required
                       true,   // It appears only once
                       true,   // It allows substitution
                       Setting.STRING);
            settingArray[1] = new Setting("resultType", "Result Type",
                    "Choose where to store result \n" +
                    "into Element or Session data",
                    true,   // It is required
                    true,   // It appears only once
                    false,  // It does NOT allow substitution
                    new String[]{"Element","Session"});//pull-down menu
            settingArray[1].setDefaultValue("Session");
            settingArray[2] = new Setting("resultEntityID", "EntityID",
              "Name of variable to hold the result.",
              true,   // It is required
              true,   // It appears only once
              true,   // It allows substitution
              Setting.STRING);  
            settingArray[2].setDefaultValue("EntityID");
            settingArray[3] = new Setting("resultMemberID", "MemberID",
                    "Name of variable to hold the result.",
                    true,   // It is required
                    true,   // It appears only once
                    true,   // It allows substitution
                    Setting.STRING);  
            settingArray[3].setDefaultValue("MemberID");
            settingArray[4] = new Setting("resultTFNType", "TFNType",
                      "Name of variable to hold the result.",
                      true,   // It is required
                      true,   // It appears only once
                      true,   // It allows substitution
                      Setting.STRING);  
            settingArray[4].setDefaultValue("TFNType");    
    return settingArray;
        public ElementData[] getElementData() throws ElementException
            return null;

  • Date Formatting, Converting from String to Timestamp

    I am trying to convert a string date to timestamp.
    I have tried a couple of different ways to arrive at the end result.
    I am basically trying to convert a date in the "dd-MM-yyyy" format to a timestamp.
    If I use the following code, I get a date like this "18-May-2004 12:00:00 AM".
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy);
    Date dContractDate = sdf.parse("18-05-2004");
    long dateInMilli = dContractDate.getTime();
    bHelp.bcontractdate = new Timestamp(dateInMilli);
    How can I make this code display the current time not midnight or some defaulted value?
    Thanks.

    I think a clever person would reuse their Date.classObject and call Date.setTime() as opposed to always
    rolling out a new Date()
    Not really a question of cleverness. Your code wins
    nothing. Objects are not magically created and garbage collected in the ether.
    The cost of creating a Date is nothing
    compared to the cost of a format() call. True, but not valid a valid statement pertaining to the issue which is
    "does always rolling dates suffer a performance hit?"
    Plus you lost clarity Maybe you loose track of your code if you don't make new Objects all the time,
    but I have never suffered from this.
    Why do you think Sun provided the setDate() method?
    and thread-safety.I have only had Thread issues when I didn't program them properly.
    Luckilly I always program the correctly ;) (Touch wood)
    The facts as I seem are thus:
    Rolling new dates on a 1.83 GHZ PC incurrs on average
    a 19% penalty. Here is the proof.
    Save this program and save it as DateTest.java
    If you don't want to waste the time here are the results of running it
    through the default 10 iterations.
    Running 10 iterations.
    Reuse of dates is 27% more efficient
    Reuse of dates is 17% more efficient
    Reuse of dates is 18% more efficient
    Reuse of dates is 20% more efficient
    Reuse of dates is 20% more efficient
    Reuse of dates is 17% more efficient
    Reuse of dates is 17% more efficient
    Reuse of dates is 20% more efficient
    Reuse of dates is 20% more efficient
    Reuse of dates is 18% more efficient
    Gaining "nothing " actually = 19% on average
    Low percent diff = 17 High percent diff = 27
    Run it 100 times and it should still be around 19%
    With the hi time being about 47% (Probably the result of garbage collecting)
    //////////////////////////////////// <PROOF> ///////////////////////////////////////
    import java.util.Date;
    public class DateTest
    DateTest()
    public int run()
    int percent = 0;
    int loopCount = 0;
    Date date = null;
    int z=0;
    long start1=0,end1=0,start2=0,end2=0,now=0;
    int time1 = 0,time2 = 0;
       now = System.currentTimeMillis();
       date = new Date(now);
       loopCount = 10000000;
       start1    = System.currentTimeMillis();
       for(z=0;z<loopCount;z++)
          now = System.currentTimeMillis();
          date.setTime(now);
       end1 = System.currentTimeMillis();
       start2    = System.currentTimeMillis();
       for(z=0;z<loopCount;z++)
          now   = System.currentTimeMillis();
          date  = new Date(now); // use 'now' so test loops are =.
       end2 = System.currentTimeMillis();
       time1 = (int)(end1 - start1);
       time2 = (int)(end2 - start2);
       percent = ((time2-time1)*100/time2);
       System.out.println("Reuse of dates is "+percent+"% more efficient");
       return percent;
    public static void main(String args[])
    int z=0;
    int lowP=100,hiP = 0;  // lowpercent/highpercent
    DateTest d = new DateTest();
    int loopCount = 0;
    long totals   = 0;
    int average   = 0;
    int values[];
    int retVal = 0;
       try // Yea olde Lazy person's command line handler :)
          loopCount = Integer.parseInt(args[0]);
       catch(Exception any)
          loopCount = 10;
       if(loopCount == 0)
          loopCount = 10;
       values = new int[loopCount];
       System.out.println("Running "+loopCount+" iterations.");
       for(z=0;z<loopCount;z++)  //
          retVal = d.run();
          if(lowP > retVal)
             lowP = retVal;
          if(hiP < retVal)
             hiP = retVal;
          values[z] = retVal;
       for(z=0;z<loopCount;z++)
          totals += (long)values[z];
       average = (int)(totals/loopCount);
       System.out.println(" Gaining \"nothing \" actually = "+average+"% on average");
       System.out.println("Low percent diff = "+lowP+" High percent diff = "+hiP);
    }////////////////////////////////// </PROOF> /////////////////////////////////////////
    Your "nothing" is in fact on average about a 19% performance hit. per call.
    These inefficiencies build up and java is infested with the,
    Was it not so the java would run much more efficiently than it now does.
    Ask yourself; why did Sun supply the setDate() method???
    (T)

  • Parse a string?

    Can you parse a string in java?

    String input = JOptionPane.showInputDialog ("Please
    enter a String");
              String x = new String(input);
              String test[] = {x};
              for (int k = 0; k < test.length; k++)
              System.out.println(test[k]);works. Simple really...thanksThis is completely different from what you previously said you wanted to do. What's the point of putting a String into a one-element String array?

Maybe you are looking for