Make Array of int's from a String

Hi,
Trying to transform a String into an array of ints. The following works, but seems a little longwinded for what must be quite a common function - specifically line 9 in the code (turning a char into an int). Can anyone suggest an easier way?
public class IntArray {
    public static void main( String[] args ) {
        if ( args.length == 1 ) {
            String s = args[ 0 ] ;
            int sLength = s.length() ;
            int[] argIntArray = new int[ sLength ] ;
            for ( int j = 0 ; j < s.length() ; j++ ) {
                // This line ...
                argIntArray [ j ] = Integer.parseInt( s.charAt( j ) + "" );
            for ( int j = 0 ; j < argIntArray.length ; j++ ) {
                System.out.println( argIntArray[ j ] );
        } else {
            System.out.print( "Please enter an int" );
}Thanks,
Rich

I'm not sure how common it is, but since you are assuming that the input is a String that represents an int...
public class IntArray {
     public static void main( String[] args ) {
          if ( args.length == 1 ) {
               String s = args[ 0 ] ;
               int sLength = s.length() ;
               int[] argIntArray = new int[ sLength ] ;
               for ( int j = 0 ; j < s.length() ; j++ ) {
                    // This line ...
                    argIntArray [ j ] = s.charAt( j ) - '0' ;
                    //I suggest checking for <0 or >9
               for ( int j = 0 ; j < argIntArray.length ; j++ ) {
                    System.out.println( argIntArray[ j ] );
          } else {
               System.out.print( "Please enter an int" );

Similar Messages

  • Dynamic Variable name (for int/long) from a String variable

    Hi,
    I want to give a int/long variable name from a String.
    for ex.
    String str = lookup + "Id";
    lookup is a String variable coming from XML. Now, for instance lookup="name". So str = "nameId".
    Now I want to create a int/long variable by nameId.
    Could anybody tell me the way how to do. Please don't tell to use MAP.
    Edited by: Shah on Dec 5, 2007 3:26 PM

    Well you can't. Use a Map.
    The compiler translates variable names into slot numbers, either within an object or withing the local "stack frame" and these slot numbers are assigned names at compile time. No new slots can be created at run time. Java is not Basic.
    Reflection allows you to find existing field names and methods (not local variables), so it's possible to map, for example, XML attribute names to field names or setters in an object but the names have to be known at compile time.

  • Extract int from a string

    Hi,
    I am curious if there is an easy way to extract an int value from a String.
    For example, "Rb23" to get 23. The length of the part in front of the integer is variable.
    Thanks

    this seems to work:
    public int extract(String s) {
         String result = "";
         char c[] = s.toCharArray();
         int j = c.length-1;
         if (!Character.isDigit(c[j])) {
              return 0;
         do {
              result+=c[j--];
         } while (j > 0 && Character.isDigit(c[j]));
         return Integer.parseInt(new StringBuffer(result).reverse().toString());
    }it will return 0 if no numbers are found at the end of the string

  • How to convert String array into int.

    void getSoldSms(Vector vecSoldSms)
         String str[]=new String[vecSoldSms.size()];
         String words[]=new String[str.length]; // String array
              for(int i=0;i< vecSoldSms.size();i++)
                   str=(String)vecSoldSms.get(i);
              }               //End for
              for(int i=0;i<str.length;i++)
              words = str[i].split("\\|\\|");
              System.out.println();
              for(int j=0;j<1;j++)     
              int count[str.length]=Integer.parseInt(words[i]);
              System.out.print(count[j]*advance_count);
              } // end inner for loop
              }          //End for
         }          //End function getSoldSms
    how do i convert words which is a string array into int type. i kno string can be converted into int using interger.parseint. but wat abt string arrays??? plz help me out with the above code.

    i did tht its still giving the same errorFor Heaven's sake, what about taking a second to try to understand the code you're copying first? If you really can't fix the error yourself, you have a more serious problem than just convertingStrings to ints.
    And if you want { "1", "2", "3" } to be 123:
    StringBuffer b = new StringBuffer();
    for (int i = 0; i < array.length; i++) {
      b.append(array);
    int result = Integer.parseIn(b.toString());

  • How do I make a Datagram Packet from a String?

    I am looking to make a Datagram Packet from a string. If I send a command to a server that allows remote connections via UDP, such as "restart" it will restart the server. I can accomplish this easily through the fput() method of PHP.
    I want a Java version of my utility, and am using the DatagramSocket and DatagramPacket classes. I see that I need to make a byte array and put it inside a DatagramPacket. How would I go about putting the string "restart" into a byte array?
    Thanks,

    Use the following code to send a Datagram:-
    import java.io.*;
    import java.net.*;
    // This class sends the specified text as a datagram to port 6010 of the
    // specified host.
    public class UDPSend {
        static final int port = 6010;
        public static void main(String args[]) throws Exception {
            if (args.length != 2) {
                System.out.println("Usage: java UDPSend <hostname> <message>");
                System.exit(0);
            // Get the internet address of the specified host
            InetAddress address = InetAddress.getByName(args[0]);
            // Convert the message to an array of bytes
            int msglen = args[1].length();
            byte[] message = new byte[msglen];
            args[1].getBytes(0, msglen, message, 0);
            // Initilize the packet with data and address
            DatagramPacket packet = new DatagramPacket(message, msglen,
                                   address, port);
            // Create a socket, and send the packet through it.
            DatagramSocket socket = new DatagramSocket();
            socket.send(packet);
    }This uses argments, if you want a string change the code accordingly.

  • How can i store values from my String into Array

    Hi guys
    i wants to store all the values from my string into an array,,,, after converting them into intergers,,,, how i can do this becs i have a peice of code which just give me a value of a character at time,,,,charat(2)...BUT i want to the values from String to store in an Array
    here is my peice of code which i m using for 1 char at time
    int[] ExampleArray2 = new int[24];
    String tempci = "Battle of Midway";
    for(int i=0;i>=tempci.length();i++)
    int ascii = tempci.charAt(i); //Get ascii value for the first character.

    public class d1
         public static final void main( String args[] )
              int[] ExampleArray2 = new int[24];
              String tempci = "Battle of Midway";
              for(int i=0;i<tempci.length();i++)
                   int ascii = tempci.charAt(i);
                   ExampleArray2=ascii;
              for(int i=0;i<ExampleArray2.length;i++)
                   System.out.println(ExampleArray2[i]);

  • Getting int values from a char array

    Hi,
    I need to make a fast program which reads lots of data from files and process them. I need to interpret these data as int's. To be more efficient and avoid to make a lot of disk access, I allocate in memory buffers part of the data, then process it and then allocate new data. The problem is that if I want to allocate data in memory buffers, all the methods that enables me to do that receceive as a parameter only a an array of chars, and as I have mentioned I need to interpret the data as a 4 bytes int. The static methods of Array to get the int value from a position ar not useful because the onlye get the int value of the indexed byte (or char); this method doesn't take 4 bytes from the index to build an int.
    My question is: is there any way to build an int from 4 bytes? or can I get the int's in this way directly from the buffer?
    Thank you,

    Isn't this one of the prime examples of using java.io.DataOutputStream and java.io.DataInputStream?

  • Make array from Timer

    How to make array from Timer. I have made but running in wrong time(always running). Task should running(using scheduling) in right time, but it's always running although the time is over.
    How to make Timer become running?
    for(int i=0;i<10;i++)
    Date dtPeriodeStart;
    ScenarioTimer st[] = new ScenarioTimer;
    Timer tmPer[] = new Timer[i];
    tmPer[i] = new Timer(true);
    Timer tmCall = tmPer[i];
    tmCall.schedule(st[i],dtPeriodeStart,delay);

    The forum formatting program eats [x] where x is an
    i and makes italics of the rest of the post. Could
    you change your post to not use i in []?Better yet, put the code in '[code]' and '[/code]' tags. See the code button above the posting box, as well as the formatting tips link above the posting box.

  • Scan arrays from binary string

    I have TCP connection that is sending a great number of fixed size arrays that I need to convert. Is there a simpler way to do that than the one I have attached?
    Attachments:
    Scan from binary string.vi ‏16 KB

    Sorry, I didn't write my question clear enough.
    I know how to do TCP data transfer. I also know how to unflatten the binary string back to data, but I was hoping there was a clearer way to do it than the way I suggested. For scalar values one can make a cluster containing the data in the binary string and only one "unflatten from string" is needed.
    However, if the binary string is composed of arrays (even though they are fixed in size) I need one unflatten string for each array. In my case I have many small arrays. The attached example with only three arrays was only to illustrate what I wanted to do.
    I have now found a way using a cluster of clusters. I don't know if this is the ideal way of doing this, but it works, and when enabling "view cluster as icon" I can make the code much more compact and easier to read
    Attachments:
    2012-07-04_120216.jpg ‏385 KB

  • How to get int value from [session.getAttribute("String")]

    i am not able to get int value from the following statiment
    int i=session.getAttribute("String");
    i also try by casting it into int but it dont work, can somebody help me in this regard

    abuu wrote:
    i am not able to get int value from the following statiment
    int i=session.getAttribute("String");
    i also try by casting it into int but it dont work, can somebody help me in this regard
    Integer i=(Integer)session.getAttribute("String");
    i.intValue();but know how it is working. that is useful.
    Diablo.

  • Getting one character at a certain position from a string array

    Hi, i'm new at learning java, but have strong experience at C++ and asm. How would i get one character at a certain positon from a string array.
    for example:
    String Phrases[] = {"To be or not to be, that is the question","The Simpsons","The Mole","Terminator three rise of the machines","The matrix"};
    that is my string array above.
    lets say i wanted to get the first character from the first element of the array which is "T", how would i get this

    ok well that didn't work, but i found getChars function can do what i want. One problem, how do i check the contents of char array defined as char Inchar[];

  • How to dynamically create a JSF dataTable from a String[][] array

    Hi, I�m developing an application that uses columns, rows and data instead of any other attributes, so I got from a database Resultset a String[] array with the rows headers, other String[] array with the columns headers, and a String[][] array with the information between every row[] and column[] header al this String arrays depend on a method that receives the group title as a parameter so they are dynamically created, anyway I can display this information in a jsp page but I don�t know how to display this information in a JSF dataTable.
    Does anybody knows how I could do this? and which is the proper way to create a dynamically rows and columns dataTable?

    Hi, I�m developing an application that uses columns, rows and data instead of any other attributes, so I got from a database Resultset a String[] array with the rows headers, other String[] array with the columns headers, and a String[][] array with the information between every row[] and column[] header al this String arrays depend on a method that receives the group title as a parameter so they are dynamically created, anyway I can display this information in a jsp page but I don�t know how to display this information in a JSF dataTable.
    Does anybody knows how I could do this? and which is the proper way to create a dynamically rows and columns dataTable?

  • Make components like JPanel / Containers ..  from a String..

    public class PuzzlePieces {
         private String area;
         private String *container* = area +"Container";
         private String panel = area +"Panel";
         private Container *container* = new Container();
         private int number;
         public PuzzlePieces(String area, int numbersOfPices) {
              this.area = area;
              this.number = numbersOfPices;
         }as you can see I want to make a Container out of a Sting. How can I do this? Please make an example if you have a solution. TY

    Plexus81 wrote:
    OK, I'll try to explain ..
    I get a string in, as you can see. I want to make/add JButton, JPanel, Containers .. based on name of the String I get in.
    String
    StringPanel
    StringContainer
    But I cant write like this
    Container String +"Container" = new Container();What's the best way to solve this..You want the variable names for those Containers to be based off the Strings? Is that what you mean? Why do you want/need to do that?
    The go-to solution for stuff like this is to use a Map of String, Container pairs. But why over complicate your program with stuff you probably don't really need?

  • Can't get an array of characters from a string!

    If I have a string eg "Hello World", how do I get an array containing the characters eg. [H,e,l,l,o, ,W,o,r,l,d]
    Can any one help me please?

    Or to get the chars you want from a String object you can do this:
    String helloString = new String("Hello World");
    char[] helloArray = helloString.toCharArray();

  • How to get the Values i need from a String???

    hi i need some help on my program,
    I have a Server that actually sent some data to my Client.
    The data consist of some messages and intergers . The whole piece of data is stores as a String message.
    ARRAY 'Monitor Chart' 2 5
    'Total OverFlow' 'Queued' 'Completed' 'Host Resets' 'Errors'''
    0.0 1.0 2.0 3.0 4.0
    'Series1' 11.0 0.6 8.6 11.5 6.6
    'Series2' 12.8 6.7 21.6 11.1 30.0Inside the Client i need to get the values out to showed on my textfields
    Example :
    Tf1 = 11.0
    Tf2 = 0.6
    Tf3 = 8.6
    Tf4 = 11.5
    Tf5 = 6.6
    Question: How to i get the values out from the String???

    using the split() method. i am able to split everything now
    so it appear somthing like this :
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class testing{
         String d1 =     "ARRAY 'Monitor Chart' 1 5";
         String d2 = "'Total OverFlow' 'Queued' 'Completed' 'Host Resets' 'Errors'";
         String d3 = "'' 0.0 1.0 2.0 3.0 4.0 ";
         String d4 = "'Series1' 11.0 0.6 8.6 11.5 6.6 ";
         String d5 = "'Series2' 12.8 6.7 21.6 11.1 30.0 ";
         String data = d1 + d2 + d3 + d4 + d5;     
         public testing(){
              System.out.println(data);
              String[] result = data.split("\\s");
              for(int x=0;x<result.length;x++)
              System.out.println(result[x]);
         public static void main (String args[])throws IOException{
            testing Application = new testing();
    }ARRAY
    'Monitor
    Chart'
    2
    5
    'Total OverFlow'
    'Queued'
    'Completed'
    'Host Resets'
    'Errors'''
    0.0
    1.0
    2.0
    3.0
    4.0
    'Series1'
    11.0
    0.6
    8.6
    11.5
    6.6
    'Series2'
    12.8
    6.7
    21.6
    11.1
    30.0
    but how do i get the values out ??how do i noe it is which index or wad?
    11.0
    0.6
    8.6
    11.5
    6.6

Maybe you are looking for

  • Multiple copies of same movie to sync to iPhone and AppleTV

    As a loyal collector of Apple "stuff", I have movies on my primary computer (PowerMac G5 w/ additional 250GB HS just for iTune media). Some of these movie files wouldn't sync to the AppleTV, so I converted the to a format/form which would sync. Some

  • Does my Macbook Air need a power converter in the UK?

    I am traveling to the UK soon - will I need a power converter for my MacBook Air, iPad and iPhone? thanks

  • My email has been lost and I can't connect to it can you help me please

    In the last twenty four hours I have not been able to receive email . A message would say that my password or email address was wrong I have repeatedly tried turning my email off and on  Now i am really lost and I need my email to be on because of sc

  • How to change the order of columns in a speadsheet?

    It seems this would be completely straight-forward. However I can find nothing in help to tell me how to do this. I am using a spreadsheet for data so want to be able to rearrange in the order of the columns. How does one do this? Thanks. John

  • Get an object in a servlet

    Hello! I'm developing a servlet which has to get an object that I send as a parameter: Course c = new Course(); out.println("<form ... action=\"InsertCourse?course="+c+"\">"); I don't know how to get mi object "c" in the servlet InsertCourse. When I