Array of String Arrays

How do I make an array of String Arrays, not knowing how big the array will be
or how big any of the arrays it contains will be at the time I create it?

The size of an array is not dynamic, i.e. if you use an array, you must know its size at the time you create it.
Use one of the collection classes (like java.util.Vector or one of the implementation classes of java.util.List).
regards
Jesper

Similar Messages

  • Cast Object Array to String Array.

    When I try to cast an object array to string array an exception is thrown. How do I go about doing it?
    Vector temp = new Vector();
    Object[] array = temp.toArray();
    String[] nonterms;                              
    nonterms = (String[])array;
    Thanks,
    Ally

    Try this
    import java.util.Vector;
    public class Test
         public static void main(String args[]) throws Exception
              Vector v = new Vector();
              v.add("a");
              v.add("b");
              v.add("c");
              Object[] terms = v.toArray();
              for(int i = 0; i < terms.length; i++)
                   System.out.println((String)terms);
    Raghu

  • How to convert an int array to string array?

    Hi,
    Can anyone please help me with this question?
    int number={4,6,45,3,2,77};
    I like to convert this into a list and sort
    List mylist = Arrays.asList(number);
    Collections.sort(mylist);
    But first I need to convert the int array to String array.
    Please advise. Thanks.

    If you want to convert your int array to a String array, you have no choice but doing a conversion element by element in a for loop.
    However, if the sort method doesn't behave as desired, you can use the one with 2 parameters, the second parameter being a comparator class.
    Check the javadoc for more information : http://java.sun.com/j2se/1.3/docs/api/java/util/Collections.html
    /Stephane

  • Read/Write 2d numeric array or string array into bin file

    Can anyone pls help me to resolve this problem
    Attachments:
    bin file.vi ‏9 KB

    You are still using the wrong format.
    Whatever you are doing has nothing to do with a binary file.
    You are still using way too much duplicate code.
    All you probably need is read/write from spreadsheet file, no need to reinvent the wheel.
    Your code will fail if the numbers contain decimal digits (since your array is DBL, it could! If your array only contains integers, you are using the wrong numeric representation).
    You string code will fail if the array elements contains tabs, for example.
    You still don't need a sequence structure.
    LabVIEW Champion . Do more with less code and in less time .

  • Problems with string array, please help!

    I have a String array floor[][], it has 20 rows and columns
    After I do some statement to modify it, I print this array
    out in JTextArea, why the output be like this?
    null* null....
    null null...
    null null...
    How to correct it?

    a turtle graphics applet:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TG extends JApplet implements ActionListener {
      private int x, y;
      private int pendown, command, movement;
      String direction, output, temp;
      JLabel l1;
      JTextField tf1;
      JTextArea ta1;
      String floor[][] = new String[20][20];;
      public void init()
        x = 0;
        y = 0;
        pendown = 0;
        direction = "r";
        Container c = getContentPane();
        c.setLayout( new FlowLayout() );
           l1 = new JLabel( "Please type a command:" );
           c.add( l1 );
           tf1 = new JTextField(20);
           tf1.addActionListener( this );
           c.add( tf1 );
           ta1 = new JTextArea(20,20);
           ta1.setEditable( false );
           c.add( ta1 );
    public void actionPerformed( ActionEvent e )
           temp = tf1.getText();
           if( temp.length() > 1)
           command = Integer.parseInt(temp.substring(0,1));
           movement = Integer.parseInt(temp.substring(2,temp.length()));
           else
           command = Integer.parseInt(temp);
           switch(command)
                case 1:
                pendown=0;
                break;
                case 2:
                pendown=1;
                break;
                case 3:
                direct("r");
                break;
                case 4:
                direct("l");
                break;
                case 5:
               move(movement);           
                break;
                case 6:
                print();
                break;                                     
      public void direct(String s)
           if(direction == "r" && s =="r")
              direction = "d";
           else if(direction == "r" && s =="l")
              direction = "u";
           else if(direction == "l" && s =="r")
              direction = "u";
           else if(direction == "l" && s =="l")
              direction = "d";
           else if(direction == "u" && s =="r")
              direction = "r";
           else if(direction == "u" && s =="l")
              direction = "l";
           else if(direction == "d" && s =="r")
              direction = "l";
           else if(direction == "d" && s =="l")
              direction = "r";
      public void move(int movement)
           if(pendown == 1)
                if(direction == "u")
                for(int b=0;b<movement;b++)
                     floor[x][y+b] = "*";
                else if(direction == "d")
                for(int b=0;b<movement;b++)
                     floor[x][y-b] = "*";
                else if(direction == "l")
                for(int b=0;b<movement;b++)
                     floor[x-b][y] = "*";
                else if(direction == "r")
                for(int b=0;b<movement;b++)
                     floor[x+b][y] = "*";
            else if(pendown == 0)
                 if(direction == "u")
                for(int b=0;b<movement;b++)
                     floor[x][y+b] = "-";
                else if(direction == "d")
                for(int b=0;b<movement;b++)
                     floor[x][y-b] = "-";
                else if(direction == "l")
                for(int b=0;b<movement;b++)
                     floor[x-b][y] = "-";
                else if(direction == "r")
                for(int b=0;b<movement;b++)
                     floor[x+b][y] = "-";
          public void print()
         for(int row=0;row<20;row++)
           for( int column=0;column<20;column++)
                output += floor[row][column];
                if(column == 19)
                 output+="\n";
            ta1.setText(output);
    }

  • Problems with string arrays

    Previous task was:
    Write a class "QuestionAnalyser" which has a method "turnAnswerToScore". This method takes a String parameter and returns an int. The int returned depends upon the parameter:
    parameter score
    "A" 1
    "B" 2
    "C" 3
    other 0
    Alright, here's the recent task:
    Write another method "turnAnswersToScore". This method takes an array of Strings as a parameter, works out the numerical score for each array entry, and adds the scores up, returning the total.
    That's my code:
    class QuestionAnalyser{
    public static int Score;
    public String[] Answer;
    public static void main(String[] args) {}
         public int turnAnswerToScore(String[] Answer)
    for (int i = 0; i < Answer.length;i++) {
    if (Answer.equals("A")) {
    Score = Score + 1; }
    else if (Answer[i].equals("B")) {
    Score = Score + 2;}
    else if (Answer[i].equals("C")) {
    Score = Score + 3;}
    else {
    Score = Score + 0;}
    return Score;
    this is the error message I get:
    The results of trying to compile your submission and run it against a set of test data was as follows:
    ----------Compilation output--------------------------------------
    javac QATest2.java
    QATest2.java:15: cannot resolve symbol
    symbol : method turnAnswersToScore (java.lang.String[])
    location: class QuestionAnalyser
    if(qa.turnAnswersToScore(task)!=total){
    ^
    What went wrong?
    Suggestions would be greatly appreciated!

    If I declare int score in the method i get this message
    The results of trying to compile your submission and run it against a set of test data was as follows:
    ----------Compilation output--------------------------------------
    javac QATest2.java
    ./QuestionAnalyser.java:20: variable score might not have been initialized
    score++; }
    ^
    ./QuestionAnalyser.java:23: variable score might not have been initialized
    score++;
    ^
    ./QuestionAnalyser.java:27: variable score might not have been initialized
    score++;
    ^
    ./QuestionAnalyser.java:34: variable score might not have been initialized
    return score;
    ^
    4 errors
    ----------Sorry expected answer was-------------------------------
    The method turnAnswersToScore is working OK - well done!
    ----------Your answer however was---------------------------------
    Exception in thread "main" java.lang.NoClassDefFoundError: QuestionAnalyser
         at QATest2.main(QATest2.java:4)
    This is the message I get from the submission page, but trying to compile it I get the same messages.
    The code looks like this, then
    class QuestionAnalyser{
    String[] answer;
    public static void main(String[] args) {}
         public int turnAnswersToScore(String[] answer)
    int score;
    for (int i = 0; i < answer.length; i++) {
    if (answer.equals("A")) {
    score++; }
    else if (answer[i].equals("B")) {
    score++;
    score++; }
    else if (answer[i].equals("C")) {
    score++;
    score++;
    score++; }
    else {}
    return score;
    When I leave 'public int score;' where it was before (right after the class declaration below the declaration of the string array) I get this but it compiles normally.
    The results of trying to compile your submission and run it against a set of test data was as follows:
    ----------Compilation output--------------------------------------
    javac QATest2.java
    ----------Sorry expected answer was-------------------------------
    The method turnAnswersToScore is working OK - well done!
    ----------Your answer however was---------------------------------
    wrong answer in turnAnswersToScore for
    BDCAADDCA
    Alright, even university students need to sleep :-)
    Good night.

  • Get numerical values from 2D array of string

    Hello! 
    I start by saying that I have a base knowledge of LabView. I'm using LabView 2011. I'm doing some communications test via Can-Bus protocol. As you can see in pictures of the block diagram and of the front panel that I've attached I'm using "Transmit Receive same Port" LabView example. It works very good but I would need to insert the 8 data bytes that I receive from the server in 8 different numerical variables so that I could use them to make some operations. How can I get numerical values from the 2D array of string that I attached? 
    Every example that you can provide is important! 
    Thank you very much! 
    Attachments:
    1.jpg ‏69 KB
    2.jpg ‏149 KB

    Hi martiflix,
    ehm: to unbundle data from a cluster I would use the function Unbundle(ByName)…
    When you are new to LabVIEW you should take all the FREE online resources offered by NI on their website!
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Remove null values from string array

    Hi ,
    I have a string array in a jsp page which I save some values inside. After I store the values I want to print only those who are not null. How can I do this? Is there a way to delete the null values?

    Thank you but because I am new in programming what do you mean to use continue. Can you explain it a little bit further?<%
    //go through the array to check all the values
    for(int i=0; i<array.length();i++) {
    //If array is null, nothing happen
    if(array==null){
    //leave here blank; instead use continue like:
    //this will skip the statements next to it, and increments the value of i in for loop and continues to execute the body of for loop.
    //The same will be repeated till the last iteration.
    continue;
    //If array not null, then print value in a new line
    else{
    out.print(array+"<br>"); //don't change the logic here
    %>

  • How do I write an array of strings to a single Excel row?

    I'd like to write test data, as an array of strings, to an Excel file. Attached is my attempt to modify one of the Labview 6.1 example files. This modified example will write the data to the correct row, which is determined by serial # of the UUT, but to a new sheet for each unit. I'd like to do the same thing, but to just one sheet. This sheet's data would then be saved after 50 rows of collected test data.
    Thank you in advance,
    Tim Denson
    Attachments:
    Write Table To XL.vi ‏58 KB

    Sorry I didn't get back to faster on this. I've been out of town working and just really haven't had time.
    Yes,
    The Report Generation toolkit would make this very easy. If you have it, I'd suggest using it.
    The image shown below shows the five VIs from the toolkit that I've used to write to Excel.
    What this loop does is receive a string through a Queue, either open a
    template or open todays file, convert the tab delimited string to an
    array, write the array to the next line of the Excel file, Save (with
    todays date stamp if opened from the tempate) and close it. It's a good
    idea to always save and close teh file after each write if it's not
    being continuously written to. In this case, a new line will be written
    only once a minute or so. This lessens the chance of losing data if the
    machine locks up for some reason. Opening and closing does take time
    and can slow down a loop that needs to run at a certain rate. This loop
    actually runs in a background process and several other processes send
    data to it through the queue to be written. The queue can buffer
    several data streams if needed so you won't lose data if it's busy and
    you don't have to worry about two processes accessing the Excel sheet
    at the same time.
    Ed
    Message Edited by Ed Dickens on 02-18-2006 11:12 AM
    Ed Dickens - Certified LabVIEW Architect - DISTek Integration, Inc. - NI Certified Alliance Partner
    Using the Abort button to stop your VI is like using a tree to stop your car. It works, but there may be consequences.
    Attachments:
    RGTK Array to Excel.gif ‏14 KB

  • 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 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

  • Exporting a String Array to an HTML file

    Hey everyone..I'm currently making lots of progress in my project...but right now I've been trying to make a button that exports my search results to an html file...basically what I've made is a search engine to search webcrawler files...
    The result list I get (which is actually a string array), I want to export to html so I can open that html file and find all the links that were found in the search I made..What I have so far is this, but it's not working yet, any help? :
        private class exportListener implements ActionListener
            public void actionPerformed(ActionEvent e)
                String[] result = parent.getResult();
                if(result == null)
                    return;
                JFileChooser chooser = new JFileChooser();
                chooser.setAcceptAllFileFilterUsed(false);
                chooser.setFileFilter(new HtmlFileFilter());
                chooser.setDialogType(JFileChooser.SAVE_DIALOG);
                int returnVal = chooser.showSaveDialog(parent);
                if(returnVal == JFileChooser.CANCEL_OPTION)
                    return;
                File fl = chooser.getSelectedFile();
                String path = fl.getPath() + ".html";
                searchIF.exportResultAsHtml(path);
                System.out.println(path);
        private class HtmlFileFilter extends FileFilter
            public String getDescription(){return "Html";}
            public boolean accept(File pathname)
                String name = pathname.getPath();
                //Just checking to see if the filename ends with html.
                if (name.toLowerCase().substring(name.lastIndexOf('.') + 1).equals("html"))
                    return true;
                return false;
            }

    Actually..nevermind, sorry.

  • Compare a String Array to get Higher value

    Hi, I'm trying to figure out how can I create a method in which I can compare my array of String by getting the higher value. For example I have an array called faces[]. What I would like to say is that if 2 is less than 5, and so forth print "blahhhh". I would appreciate some ideas on which is the best way to do this. Thanks a lot. Here is the code so far. I'm working on checkWinner() method
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class WarCard extends JFrame implements ActionListener {
         private Card deck[];
         private int currentCard, value, winner;
         private JPanel buttonPanel, labelPanel, textFieldPanel;
         private JButton buttons[];
         private JLabel labels[];
         private JTextField textFields[];
         public WarCard()
              super( "War! " );
              String faces[] = { "Ace", "Deuce", "Three", "Four", "Five", "Six",
                   "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
              String suits[] = { "Hearts", "Diamonds", "Clubs", "Spades" };
              deck = new Card[ 52 ];
              currentCard = -1;
              //populate deck
              for ( int count = 0 ; count < deck.length; count++ )
                   deck[ count ] = new Card( faces[ count % 13], suits[ count / 13 ] );
              // get content pane and create layout
              Container container = getContentPane();
              // create label grid
              labels = new JLabel[3];
                   labels[ 0 ] = new JLabel( "Player 1: ");
                   labels[ 1 ] = new JLabel( "Player 2: ");
                   labels[ 2 ] = new JLabel( "Shuffle cards to begin" );
              labelPanel = new JPanel();
              labelPanel.setLayout( new GridLayout( 3, labels.length ) );
              for ( int count = 0; count < labels.length; count++) {
                   labelPanel.add( labels[ count ] );
              }// end for loop
              container.add( labelPanel, BorderLayout.WEST );
              // create text field grid
              textFields = new JTextField[ 3 ];
                   textFields[ 0 ] = new JTextField( 20 );
                   textFields[ 1 ] = new JTextField( 20 );
                   textFields[ 2 ] = new JTextField( 20 );
              textFieldPanel = new JPanel();
              textFieldPanel.setLayout( new GridLayout( 3, textFields.length ) );
              for ( int count = 0; count < textFields.length; count++) {
                   textFields[ count ].setEditable( false );
                   textFieldPanel.add( textFields[ count ] );
              }// end for loop
              container.add( textFieldPanel, BorderLayout.EAST );     
              // create button grid          
              buttons = new JButton[ 3 ];
                   buttons[ 0 ] = new JButton( "Deal" );
                   buttons[ 1 ] = new JButton( "Shuffle" );
                   buttons[ 2 ] = new JButton( "Exit" );
              buttonPanel = new JPanel();
              buttonPanel.setLayout( new GridLayout( 1, buttons.length ) );
              for ( int count = 0; count < buttons.length; count++) {
                   buttons[ count ].addActionListener( this );
                   buttons[ 0 ].setEnabled( false );
                   buttonPanel.add( buttons[ count ] );
              }// end for loop
              container.add( buttonPanel, BorderLayout.SOUTH );
              setSize( 425, 150 );
              setVisible( true );
        private void checkWinner()
            int i = 0;
            for( i=0; i < 13; i++ ){
             if ( s[ 0 ].equals("2 of Spades") & s[ 1 ]!="2 of Spades" ){
                    txtGame[ 2 ].setText( " You Win " );
              else{
                   txtGame[ 2 ].setText( " Compuer Win" );
         public static void main( String agrs[] )
              WarCard application = new WarCard();
              application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         public void actionPerformed( ActionEvent event)
              String testString = "";
              for ( int count = 0; count < buttons.length; count++) {
                   if ( event.getSource() == buttons[ 0 ] ) {
                        Card dealt1 = dealPlayer1();
                        Card dealt2 = dealPlayer1();
                        if ( dealt1 != null || dealt2 != null ) {
                             textFields[ 0 ].setText( dealt1.toString() );
                             textFields[ 1 ].setText( dealt2.toString() );
                             labels[ 2 ].setText( "# of Cards : " + currentCard);
                        else {
                             textFields[ 2 ].setText( "All Cards Dealt" );
                             labels[ 2 ].setText( "Shuffle Cards to continue" );
                   else if ( event.getSource() == buttons[ 1 ] ) {
                        shuffle();
                        textFields[ 0 ].setText( " " );
                        textFields[ 1 ].setText( " " );
                        labels[ 2 ].setText( "Shuffled!");
                   else if ( event.getSource() == buttons[ 2 ] ) {
                        System.exit( 0 );
              }// end for loop
         }// end method actionPerformed
              private void shuffle()
              currentCard = -1;
              for ( int first = 0; first < deck.length; first++ ) {
                   int second = ( int ) ( Math.random() * 52 );
                   Card temp = deck[ first ];
                   deck[ first ] = deck[ second ];
                   deck[ second ]= temp;
              buttons[ 0 ].setEnabled( true );
         private Card dealPlayer1()
              if ( ++currentCard < deck.length )
                   return deck[ currentCard ];
              else {
                   buttons[ 0 ].setEnabled( false );
                   return null;
    }// end of WarCard
    class Card{
         private String face;
         private String suit;
         public Card( String cardFace, String cardSuit )
              face = cardFace;
              suit = cardSuit;
         public String toString()
              return face + " of " + suit;
         }// end toString
    }// end class WarCard

    assign an int value to the card and use < == >

  • How to populate items in selectOneListBox from a string array

    Hi
    I have got a string array result[] .Now i wish to display the array items in selectOneListBox.Please help me?

    Alance wrote:
    Hi
    I have got a string array result[] .Now i wish to display the array items in selectOneListBox.Please help me?I can only guess what your selectOneListBox is but if it is JComboBox - have you ever thought about reading the API ?
    [http://java.sun.com/javase/6/docs/api/javax/swing/JComboBox.html]
    There's a wonderful constructor which probably does what you are looking for.

  • How to populate string array in table view.

    Hi,
    By using webservice i am able to get an array of strings but, I am unable to populate those values in the tableview.
    Can any one please suggest me how to populate array of strings in table view with an example.
    Thanks,
    SRI.

    Search this forum. You will find plenty of threads on the same...
    Raja

Maybe you are looking for