How to add elements into java string array?

I open a file and want to put the contents in a string array. I tried as below.
String[] names;
s = new Scanner(new BufferedReader(new FileReader("outfile.txt")));
while (s.hasNext()) {
                String item = s.next();
                item.trim();
                email = item;
                names = email;
            }But I know that this is a wrong way of adding elements into my string array names []. How do I do it? Thanks.

Actually you cannot increase the size of a String array. But you can create a temp array with the lengt = lengthofarray+1 and use arraycopy method to copy all elements to new array, then you can assign the value of string at the end of the temp array
I would use this one:
String [] sArray = null;
s = new Scanner(new BufferedReader(new FileReader("outfile.txt")));
while (s.hasNext()) {
    String item = s.next();
    item.trim();
    email = item;
    sArray = addToStringArray(sArray, email);
* Method for increasing the size of a String Array with the given string.
* Given string will be added at the end of the String array.
* @param sArray String array to be increased. If null, an array will be returned with one element: String s
* @param s String to be added to the end of the array. If null, sArray will be returned.(No change)
* @return sArray increased with String s
public String[] addToStringArray (String[] sArray, String s){
     if (sArray == null){
          if (s!= null){
               String[] temp = {s};
               return temp;
          }else{
               return null;
     }else{
          if (s!= null){
               String[] temp = new String[sArray.length+1];
               System.arraycopy(sArray,0,temp,0,sArray.length);
               temp[temp.length-1] = s;
               return temp;
          }else{
               return sArray;
}Edited by: mimdalli on May 4, 2009 8:22 AM
Edited by: mimdalli on May 4, 2009 8:26 AM
Edited by: mimdalli on May 4, 2009 8:27 AM

Similar Messages

  • How to add elements into Object[][] type of list, in runtime?

    I have Object list, ie.
        final Object[][] data = {
            {"January",   new Integer(150) },
            {"February",  new Integer(500) },
            {"March",     new Integer(54)  },
            {"April",     new Integer(-50) }
        };How can I dynamicly add new elements in it, at the runtime?
    Thank you in advance!

    Do I have to remove 'final' for that, and then add
    elements?
    No. you can't change an array's size.
    You can do this
    Object[][] arr = new Object[numRows][numCols];But once you've created it, its size can't change.*
    I don't know what you're doing, though, and what actual data you're putting in, but Object[][] holding rows of [String, Integer] is almost certainly a poor data structure. Think about creating a class the represents one "row" here and then create a 1D array of that class.
    * Okay, you can kinda sorta effectively "change" the size of second and subsequent dimensions, since a multidimensional array is an array of arrays. I wouldn't recommend it though: int[][] arr = new int[3][2]; // a 3 x 2 rectangular array of int--it's  an array of array of int, with 3 "rows", each of which is an array of int with 2 elements.
    arr[0] = new int[10]; // now it's a jagged array whose first row has 10 elments instead of 2Here we haven't changed an array's size, just replaced one of its elements, which is also an array, with a new, larger array.

  • How to add newline into a string

    I need to define a string which contains a newline,
    what i did is :
    String newline = new String();
    newline = "\n";
    but when i add new line to other string, and print it out,
    seems it is not working....
    Anrybody knows why?
    thanks~

    Please keep in mind that newlines differ between platforms. The "\n" is very well known, however in the Windows world a newline is actually "\r\n". Thankfully you may retrieve this value from the JVM.
    String newline = System.getProperty("line.seperator");Also System.out.println() will automatically append the correct newline at the end.
    Meaning that
    System.out.println("Hello");
    System.out.print("Hello" + newline);are esentially the same.

  • How do you store input from keyboard into a string array

    I am trying to learn java and one of the programs I am trying to write needs to be able to accept a machine hostname at the keyboard and stuff it into a string array element. I am sure I will be using something along the lines of:
    BufferedReader in = new BufferedReader(new InputStreamReader(
                             System.in));
                   String str = "";
                   System.out.print("Enter a FQDN to look up: ");
                   str = in.readLine();
    but how do I get the input stuffed into hostname[ ].
    Any hints or assistance will be appreciated.
    Michael

    Well part of. I need to be able to take a random number of hostnames (ie. mblack.mkblack.com, fred.mblack.com, joe.mblack.com, ...) and after the user presses the enter key between each entry, the inputted information is stored in an array element. for example with the three shown above the array would look like this after the user finished.
    hostname {"mblack.mblack.com","fred.mblack.com","joe.mblack.com"};
    the algorithm would be
    Prompt for hostname
    get user input and press enter
    store hostname into array element
    prompt for next hostname or enter with no input to complete entry and execute lookup.class methods.
    I have the program written and working fine if I use a static array where I put the hostnames in the list, but cannot figure out how to get the information from the keyboard to the array element.
    Thanks for the help though, the response is very much appreciated.
    Michael

  • How to add images into a java application (not applet)

    Hello,
    I am new in java programming. I would like to know how to add images into a java application (not an applet). If i could get an standard example about how to add a image to a java application, I would apreciated it. Any help will be greatly apreciated.
    Thank you,
    Oscar

    Your' better off looking in the java 2d forum.
    package images;
    import java.awt.*;
    import java.awt.image.*;
    import java.io.FileInputStream;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    /** * LogoImage is a class that is used to load images into the program */
    public class LogoImage extends JPanel {
         private BufferedImage image;
         private int factor = 1; /** Creates a new instance of ImagePanel */
         public LogoImage() {
              this(new Dimension(600, 50));
         public LogoImage(Dimension sz) {
              //setBackground(Color.green);      
              setPreferredSize(sz);
         public void setImage(BufferedImage im) {
              image = im;
              if (im != null) {
                   setPreferredSize(
                        new Dimension(image.getWidth(), image.getHeight()));
              } else {
                   setPreferredSize(new Dimension(200, 200));
         public void setImageSizeFactor(int factor) {
              this.factor = factor;
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              //paint background 
              Graphics2D g2D = (Graphics2D) g;
              //Draw image at its natural size first. 
              if (image != null) {
                   g2D.drawImage(image, null, 0, 0);
         public static LogoImage createImage(String filename) { /* Stream the logo gif file into an image object */
              LogoImage logoImage = new LogoImage();
              BufferedImage image;
              try {
                   FileInputStream fileInput =
                        new FileInputStream("images/" + filename);
                   image = ImageIO.read(fileInput);
                   logoImage =
                        new LogoImage(
                             new Dimension(image.getWidth(), image.getHeight()));
                   fileInput.close();
                   logoImage.setImage(image);
              } catch (Exception e) {
                   System.err.println(e);
              return logoImage;
         public static void main(String[] args) {
              JFrame jf = new JFrame("testImage");
              Container cp = jf.getContentPane();
              cp.add(LogoImage.createImage("logo.gif"), BorderLayout.CENTER);
              jf.setVisible(true);
              jf.pack();
    }Now you can use this class anywhere in your pgram to add a JPanel

  • How to declare and initialize a STRING ARRAY (assign strings to array elements)

    How to declare and initialize a STRING ARRAY (assign desired strings to elements of an array, for example "abc", "def", "ghi", "jkl", etc.) in LabVIEW? I saw a "string array" block in help, but could not find it in the function palette. Does a spreadsheet string have to be in a file (or can it be in a string constant block)? Thank you.

    Hi,
    you can do it in several ways:
    1. Direct way: Create string array control on front panel and type strings in its elements
    2. Programmatically 1: Create string array indicator (or local variable of control), right click on it in block diagram, select "Create constant" from drop down menu. The array constant will appear. Now type values in this constant's strings
    3. Programmatically 1: Use "Build array", "Replace array subset", "Insert into array" or "Initialize array" functions from "Functions->Array" palette.
    And of course you can combine all of these methods.
    Good luck.
    Oleg Chutko.

  • How to add TickMark into dropdownlist?

    Hello,
    i am looking for dropdownlist with multiple selection.
    Is there a DropDownList widget allows more than one menu item to be selected at a time?
    i got ans from forum
    http://forums.adobe.com/message/3319311#3319311
    they said we can add tickmark into dropdownlist.so that we can select more than one item.But How to add Tickmark into dropdownlist? OR can we custmize dropdownlist?
    please, give some hint.
    If Anybody knows the solution , please help me.

    I think there are two ways:
    1) Use a specific control with text tokenization, like a Telerik's one  RadAutoCompleteBox (user1's text is a token, and user2's text is an editable
    text area);
    2) Use CSR (client-side rendering; JSLink field of a list EditForm's web part) to make the original field (input tag) read only and dynamically add second text
    box for user2's editable text. Then on form submit you can combine the two values: read only one and dynamically edited. You may do so via overriding the PreSaveAction() JavaScript function in your JSLink file.
    v

  • How to add gaussian white noise to array of one's and negative one's ?

    how to add gaussian white noise to array of one's and negative one's ?
    Solved!
    Go to Solution.

    Is it this that your are trying to accomplish:
    TO:
    Here's the code to do that.
    Michel

  • Combining string array elements into one string

    Right, I have an string array called str which stores 1 character in each of its 16 elements. It gets this character from another array, strArray. Now, what I want to be able to do is to take all 16 elements and combine them into one string called keyString. Using the code below keyString only prints out the last character. The code is shown below:
    for (x=0; x<16; x++) {
         str = new String[16];
         str[x] = "";
         str[x] += (strArray[(index+x)%16].charAt(strChar[x]));
         keyString = str[x];
           System.out.print(keyString);
    }Any help would be very much appreciated.
    Edited by: Paragon96 on May 20, 2008 7:32 AM

    your logic is wrong ; if you want to concatenate the content of the array, you have to loop (what you did), and concatenate keyString for each index, meaning:
    keyString += str[x];you can also use a StringBuilder for such kind of operations

  • How to insert elements into an array after each iteration of a for loop

    I am new to labview and working on an application where I am supposed to store an element into an array (without overwriting) after each iteration in a for loop. I have tried using Build Array Function keeping the indicator outside the for loop and played with indexing but didn't work. Please suggest me an idea how to do it.
    Thanks
    Solved!
    Go to Solution.

    Thank you for your suggestion.Here is my actual application attached . In the first image, a difference in time is evaluated and an enum const of insert into array is passed to the shift register where it takes to Insert element into array phase (Second image). I need to enter the time difference into an array after every loop iteration. Please have a look and could you let me know where I am mislead.
    Attachments:
    Image 1.JPG ‏88 KB
    Image 2.JPG ‏71 KB

  • How to add data into a List box

    CS3 SDk:Windows<br /><br />Hi all,<br />I am trying to add  data into a basic List box in CS3??<br /><br />// .fr<br />GenericPanelWidget<br />     (<br />     // CControlView properties<br />     kInvalidWidgetID, // widget ID<br />     kPMRsrcID_None, // PMRsrc ID<br />     kBindNone, // frame binding<br />     Frame(0,0,250,90) // left, top, right, bottom<br />     kTrue, // visible<br />     kTrue, // enabled<br />     // GroupPanelAttributes properties<br />     "", // header widget ID<br />     { <br />     <br />     WidgetListBoxWidgetN<br />     (<br />     kWFPListBoxWidgetID, kSysListBoxPMRsrcId, // WidgetId,RsrcId<br />     kBindAll, // Frame binding<br />     Frame(0,0,250,90) // Frame<br />     kTrue, kTrue, // Visible, Enabled<br />     1,0, // List dimensions<br />     19, // Cell height<br />     1, // Border width<br />     kFalse,kTrue, // Has scroll bar (h,v)<br />     kTrue, // Multiselection<br />     kTrue, // List items can be reordered<br />     kTrue, // Draggable to new/delete buttons<br />     kFalse, // Drag/Dropable to other windows<br />     kTrue, // An item always has to be selected<br />     kFalse,// Don't notify on reselect<br />     kFalse, <br />     {               <br />     }     <br />                    <br />),<br />},<br />),<br /><br />//-------ID.h--------<br />DECLARE_PMID(kWidgetIDSpace, kWFPListBoxWidgetID, kWFPPrefix + 2)<br /><br />//observer.cpp-----------WFPDialogObserver::Update<br /><br />//get currently selected/active widget <br />WidgetID theSelectedWidget = controlView->GetWidgetID();<br /><br />// ist it the text edit field? <br />if (theSelectedWidget == kWFPInsertButtonWidgetID && theChange == kTrueStateMessage) <br />{ <br /><br />IControlView* listBox = panelControlData->FindWidget(kWFPListBoxWidgetID);<br /><br />InterfacePtr<IListControlData> listControlData(listBox, UseDefaultIID()); <br /><br />//Insert the string into listbox <br />PMString strText = dialogCtrl->GetTextControlData(kWFPTextEditBoxWidgetID); <br /><br />// obviously there can't be a translation for text entered by user <br />strText.SetTranslatable(kFalse);<br />listControlData->Add(strText,kWFPTextEditBoxWidgetID); <br />dialogCtrl->SetTextControlData(kWFPTextEditBoxWidgetID, ""); <br />break;      <br /><br />I am not able to Add items into list box.<br /><br />I tried based on Discussion <br />http://www.adobeforums.com/webx/.3bc43877<br /><br />but not able to locate  SDKListBoxHelper file .it is not available in SDK.<br /><br />Please ,<br />Tell me Where I am going wrong.<br /><br />Thanks,<br />Adil

    resource VSPDialogWidget (kSDKDefDialogResourceID + index_enUS)
         __FILE__,
         __LINE__,
         kVSPDialogWidgetID, // WidgetID
         kPMRsrcID_None, // RsrcID
         kBindNone, // Binding
         Frame(5,0,491,266) // Frame (l,t,r,b)
         kTrue,
         kTrue, // Visible, Enabled
         kVSPDialogTitleKey, // Dialog name
              DefaultButtonWidget
                   kOKButtonWidgetID, // WidgetID
                   kSysButtonPMRsrcId, // RsrcID
                   kBindNone, // Binding
                   Frame(9,234,89,254) // Frame (l,t,r,b)
                   kTrue,
                   kTrue, // Visible, Enabled
                   kSDKDefOKButtonApplicationKey,  // Button text
              CancelButtonWidget
                   kCancelButton_WidgetID, // WidgetID
                   kSysButtonPMRsrcId, // RsrcID
                   kBindNone, // Binding
                   Frame(394,234,474,254) // Frame (l,t,r,b)
                   kTrue,
                   kTrue, // Visible, Enabled
                   kSDKDefCancelButtonApplicationKey, // Button name
                   kTrue,  // Change to Reset on option-click.
              WLBCmpListBox   //Tree view
                   kWLBCmpListBoxWidgetID, kPMRsrcID_None,     // WidgetId, RsrcId
                   kBindAll,                                                       // Frame binding
                   Frame(299,49,475,170)           // Frame
                   kTrue, kTrue,                                             // Visible, Enabled
                   kTrue,                               // EraseBeforeDraw
                   kInterfacePaletteFill,           // InterfaceColor
                   kHideRootNode | kDrawEndLine,     // Options. Display root node
                   kFalse,          // Use H Scroll bar
                   kTrue,          // Use V scroll bar
                   20,               // fVScrollButtonIncrement
                   20,               // fVThumbScrollIncrement
                   0,               // fHScrollButtonIncrement
                   0,               // fHThumbScrollIncrement
                   2,               // Items selectable, 0 = No Selection, 1 = Single Selection, 2 = Multiple Selection
                   kFalse,          // Allow children from multiple parents to be selected
                   kTrue,          // Allow discontiguous selection
                        //The tree view is dynamically created.          
    // added to support the list elements in the list box
    resource LocaleIndex (kWLBCmpListElementRsrcID)
         kViewRsrcType,
              kWildFS, k_Wild, kWLBCmpListElementRsrcID + index_enUS
    resource WLBCmpNodeWidget (kWLBCmpListElementRsrcID + index_enUS)
         __FILE__, __LINE__,
         kWLBCmpListParentWidgetId, kPMRsrcID_None,     // WidgetId, RsrcId
         kBindLeft | kBindRight,               // Frame binding
         Frame(0, 0, 194, 20),               // Frame
         kTrue, kTrue,                         // Visible, Enabled
         "",                                        // Panel name
                   // Just a info-static text widget with about-box text view to get white bg.
              WLBCmpTextWidget
                   kWLBCmpTextWidgetID, kPMRsrcID_None,          // WidgetId, RsrcId
                   kBindLeft | kBindRight,                                        // Frame binding
                   Frame(45,1,194,18)                                             // Frame
                   kTrue, kTrue, kAlignLeft,kEllipsizeEnd                    // Visible, Enabled, Ellipsize style
                   "",                                                                 // Initial text
                   0,                                                                 // Associated widget for focus
                   kPaletteWindowSystemScriptFontId,                         // default font
                   kPaletteWindowSystemScriptHiliteFontId,                    // for highlight state.
    If you still got problems, post you email here - I'll send you the complete project/code then.
    -Marc

  • How to convert BLOB into a String

    Hi,
    I got a blob column from the database.
    It contains one XML File.
    How to convert it into String.
    I need the code for how to convert the blob into String
    Thanks in Advance.

    A blob would be a byte-array, which you can use in the String(byte[]) constructor

  • WebService problem: only the first element of a string array is returned

    Hello,
    i did the J2EE QuickCarRental tutorial and extended it by some features: I created another entity bean and implemented four new methods in the QuickOrderProcessor. Then i deployed it as a WebService and accessed it using the Visual Composer.
    Everything works fine except the return value of one WebService method. I created a method with the return value String[]. But the Visual Composer reads it as String. Only the first element of the resulting string array is displayed. Although the test at the web-page http://<server>:<port>/QuickCarRentalService/Config1 displays the whole string array with all its elements. What did i wrong?
    Another problem is that after deploying the J2EE-Application with new WebService methods the changes are not visible inside the visual composer. Although the test at the web-page http://<server>:<port>/QuickCarRentalService/Config1 displays the changes. Do i have to restart the WebService system in the portal content? If yes how can i do that?

    Here are details about setting up and using web services and some examples:
    /people/prakash.darji/blog/2006/10/10/external-web-service-proxy-configuration-for-visual-composer

  • REG: How to add elements onto htmlb table cell.. URGENT PLZ HELP

    Hi all,
    I have created a htmlb table. And the jsp code is as follows
    <%@ taglib uri="tagLib" prefix="hbj" %>
    <jsp:useBean id="myBean" scope="application" class="com.linde.myaccounts.util.TableBean" />
    <hbj:content id="myContext">
      <hbj:page title="PageTitle">
       <hbj:form id="myFormId" >
       <hbj:tableView id="myTableView1"
                          model="myBean.model"
                          design="ALTERNATING"
                          headerVisible="false"
                          footerVisible="false"
                          fillUpEmptyRows="true"
                          visibleFirstRow="1"
                          visibleRowCount="5"
    </hbj:form>
      </hbj:page>
    </hbj:content>
                          width="500 px" >
    </hbj:tableView>
    I have used a table bean by which I am getting the column header names. I have 5 columns, I have to add input field in the first column, checkbox in the second column, leave the third column blank, checkbox in the fourth column and again a input field in the fifth column. I am not understanding on how to add this elements onto the table. Will I add it from the JSP using <hbj:tableViewColumns> tag or I have add them in the bean or in the dynpage. Kindly someone give me the code for this...
    This is very urgent..Kindly help...
    Thanks in advance,
    Priyanka

    Hi,
    Have you tried looking at the examples that come with the PDK for all of the HTMLB elements?  From memory, there should be a small table example or 2 that have different types of columns shown similar to what you want - they have the full source code with them for you to look at.
    If you are working in a portal, go to the Java Developer tab and I "think" there should be a tab linking to HTMLB documentation and examples - sorry I can't be more specific but I don't have access to a portal at the moment so am trying to remember.
    Gareth.

  • Combining two StringBuffer array elements into a single array element

    I just need to know how to combine two stringBuffer array elements into one
    StringBuffer ciphertext [] = new StringBuffer[2];
              StringBuffer s0 = new StringBuffer("11011111111110001001101110110101");
              StringBuffer s1 = new StringBuffer("00010011001101000101011101111001");
              ciphertext[0] = s0;
              ciphertext[1] = s1;
              ciphertext[2] = ciphertext[0].append(ciphertext[1]);I get an array index out of bounds exception:2
    Thanks

    StringBuffer ciphertext [] = new StringBuffer[3];  // legal index values are: 0,1,2

Maybe you are looking for

  • Scanner doesn't work properly

    Hello When I want to scan a new document via my HP scanner I unplug my webcam usb cable and reconnect my scanner to my PC.but when I press scan button on my scanner nothing appear(It doesn't start new scan windows) and when I open "windows fax and sc

  • Any way to open new browser window without using image maps?

    Is there any way to open new browser window without using image maps? My code works fine in Firefox, but not in IE. There are 2 problems in IE: 1st is that the thumbnail images move up within their own borders & 2nd that when you click on an image it

  • Cannot start listener

    I got the foll-error when i try to start listener.. TNS-12537: TNS:connection closed TNS-12560: TNS:protocol adapter error TNS-00507: Connection closed Linux Error: 29: Illegal seek Any one could give some tips to overcome this Thanks Ramya

  • An unhandled win32 exception occurred in fndsm.exe[5364]

    Hi, When I installed discoverer 10g on EBS 12..1.1 an unhandled win32 exception occurred in fndsm.exe[5364] comes... after installation of discoverer -- Inactive No manager comes when submit reports.. i uninstalled discoverer and EBS works fine..Plea

  • Mail App Crashes in iOS 7.1

    Hi I'm currently using an iPhone 4S, and recently updated to iOS 7.1 and the default mail app crashes, and after one crash I'm able use the app. Any ideas as to what could be causing such an issue, or should I just try and restore the iOS?