String array, integer index

class TetrisBoard {
     public static void main(String[] args) {
          String board[][] = new String[5][5];
          int column;
          int row;
          char piece;
          String board[][] = {{"| ","| ","| ","| ","| ",},
                                   {"| ","| ","| ","| ","| ",},
                                   {"| ","| ","| ","| ","| ",},
                                   {"| ","| ","| ","| ","| ",},
                                   {"| ","| ","| ","| ","| ",}};
          for(int row = 0; row < board.length; row ++) {
               for(int col = 0; col < board[row].length; col++) {
               System.out.print(board[row][col]);
}hey, this is the code i have. How do i make the indexes be integers, so that board[row][col] is compatible with String board[5][5]? thanks for the help :D

You are declaring the variable 'board' twice. Thats the first problem.
The second is you have to use the array constatant only when initializing the array.
Do this instead
class TetrisBoard {
     public static void main(String[] args) {
          String board[][] = new String[][]
               { "| ", "| ", "| ", "| ", "| ", },
               { "| ", "| ", "| ", "| ", "| ", },
               { "| ", "| ", "| ", "| ", "| ", },
               { "| ", "| ", "| ", "| ", "| ", },
               { "| ", "| ", "| ", "| ", "| ", }
...- Roy

Similar Messages

  • Getting index of a string array based on user selection in a comboBox

    I'm not really sure how to phrase my questions, but here goes.
    I have created a string array that holds the values of a ComboBox. Based on which selection the user makes in the comboBox, I need the program to then perform particular calcualtions (based on their selection). I have tried using an ItemListener, but that doesn't seem to work. I've also tried using the ActionListener connected to the ComboBox, again...without results. I'm not sure what I'm looking for exactly, but I know what I want it to do, I'm just not finding the right way to do it. Can anyone help me figure this out?

    Here is my entire code. I'm completely confused at where to put the ActionListener or how to make it do what I want. Right now I just have it set up to display a simple message in the displayArea, just so that I could see if it was working. I think once I figure out how to get the right index from the ComboBox array, then I'll be able to add the code I need to perform the calcualtions...it's just getting to that step that's not going so well! Any help is appreciated.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.DecimalFormat;
    import java.lang.String;
    public class MortCalcSR5 extends JFrame implements ActionListener
         int term = 0;
         double principal = 0;
         double rate = 0;
         double monthlyPyment = 0;
         double interest = 0;
         String[] loanChoices = {" ", "7 years @ 5.35%", "15 years @ 5.5%", "30 years @ 5.75%"};
         //create panel for input
         JPanel inputPanel = new JPanel();
              JLabel mortAmtLabel = new JLabel("Mortgage Amount $");
              JTextField mortAmtField = new JTextField(15);
              JLabel loanSelectionLabel = new JLabel("Loan Selection");
              JComboBox loanSelection = new JComboBox(loanChoices);
              JTextField loanSelected = new JTextField(15);
         //create button panel
         JPanel buttonPanel = new JPanel();
              JButton calcButton = new JButton("Calculate");
              JButton clearButton = new JButton("Clear");
              JButton exitButton = new JButton("Exit");
         //create panel for payment information
         JPanel paymentPanel = new JPanel();
              JLabel paymentLabel = new JLabel("Monthly Payment $");
              JTextField paymentField = new JTextField(15);
         //create panel for text box information
         JPanel textPanel = new JPanel();
              JLabel numPaymentLabel = new JLabel("Payment #");
              JLabel balLabel = new JLabel("Balance");
              JLabel ytdPrincLabel = new JLabel("Principal");
              JLabel ytdIntLabel = new JLabel("Interest");
         //create payment for display area
         JPanel displayPanel = new JPanel(new FlowLayout());
              JTextArea displayArea = new JTextArea(10,30);
              JScrollPane scroll = new JScrollPane(displayArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
         public MortCalcSR5()
              //set size of GUI display
              setSize(400,450);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Container pane = getContentPane();
              JScrollPane scroll = new JScrollPane (displayArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              FlowLayout layout = new FlowLayout(FlowLayout.LEFT);
              pane.setLayout(layout);
              //add components to the inputPanel
              GridLayout layout2 = new GridLayout(4,1);
              inputPanel.setLayout(layout2);
              inputPanel.add(mortAmtLabel);
              inputPanel.add(mortAmtField);
              mortAmtField.setText(" ");
              inputPanel.add(loanSelectionLabel);
              inputPanel.add(loanSelection);
              loanSelection.addActionListener(this);
              pane.add(inputPanel);
              //add components to buttonPanel
              FlowLayout layout3 = new FlowLayout(FlowLayout.CENTER, 10, 10);
              buttonPanel.setLayout(layout3);
              buttonPanel.add(calcButton);
              buttonPanel.add(clearButton);
              buttonPanel.add(exitButton);
              pane.add(buttonPanel);
              //add listeners to buttons
              calcButton.addActionListener(this);
              clearButton.addActionListener(this);
              exitButton.addActionListener(this);
              //add components to outputPanel
              FlowLayout layout4 = new FlowLayout(FlowLayout.LEFT, 10,10);
              paymentPanel.setLayout(layout4);
              paymentPanel.add(paymentLabel);
              paymentPanel.add(paymentField);
              pane.add(paymentPanel);
              //add components to textPanel
              FlowLayout layout5 = new FlowLayout(FlowLayout.LEFT, 10,10);
              textPanel.setLayout(layout5);
              textPanel.add(balLabel);
              textPanel.add(ytdPrincLabel);
              textPanel.add(ytdIntLabel);
              pane.add(textPanel);
              //add components to displayPanel
              FlowLayout layout6 = new FlowLayout(FlowLayout.CENTER,10,10);
              displayPanel.setLayout(layout6);
              displayPanel.add(scroll);
              pane.add(displayPanel);
              setContentPane(pane);
              setVisible(true);
         public void actionPerformed(ActionEvent event)
              String fs = (String)loanSelection.getSelectedItem();
              if (fs.equals("7 years @ 5.35%"))          {
                   displayArea.setText("yay");
              else
                   displayArea.setText("blah");
              JButton command = (JButton)event.getSource();
              if(command==calcButton)  //calculate button clicked - run payment event
                   Payment();
              if(command==clearButton) //clear button clicked - clear all fields
                   mortAmtField.setText(null);
                   paymentField.setText(null);
                   displayArea.setText(null);
                   loanSelected.setText(null);  //hidden text field still needs to be cleared
                   //loanChoices = null;
              if(command==exitButton)  //exit button clicked - exit program
                   System.exit(0);
         public void Payment()
              //perform the calculations
    //          int mortAmt = Integer.parseInt(mortAmtField.getText());
         //     double loanSelect = Double.parseDouble((String)loanSelected.getText());
              displayArea.append("Calcualations performed!");
         public static void main(String[] args)
              new MortCalcSR5();
    /*/calculations
         int mortAmt = Integer.parseInt(mortAmtField.getText());  //get text user entered in mortAmt field - parse it from a string to integer
         int loanTerm = Integer.parseInt(loanTermField.getText());  //get text user entered in loanTerm field - parse it from a string to integer
         double interestRate = Double.parseDouble(interestRateField.getText());  //get text user entered in interestRate field - parse it from a string to double
         int moTerm = (loanTerm*12);  //calculate monthly loan term
         double moInterest = ((interestRate/100)/12);  //calculate monthly interest rate
         double payment = mortAmt*(moInterest/(1-Math.pow(1/(1+moInterest), moTerm)));  //calculate monthly payment amount
         valid = true;  //number format is accepted
         paymentField.setText(Double.toString(payment));  //display output
    */

  • Int to string to string array

    Sorry, if my question is too wordy.
    First, the problem -- I am reading integers into my application and converting the those into strings using valueOf(). I then need to use those strings in a switch statment. The only way I could figure how to do this was to use the same String variable in each switch statement but change the the message to fit each case. My professor suggested I use an array list instead.
    Second, the question -- how can I convert the String I have generated into a String Array and use the indexing of the array to correspond to the specific text for each case?
    Thank you.

    indeed, you can't use the switch mechanism on strings.
    but, if the requirement is that you convert an integer into a string and then switch on those (I don't know why...) from an array of the values, swap the String value back into an int and switch from there.

  • Sorting string array

    Hi.
    I need a little SORT help.
    I would like to sort "f1". The file names is like this:
    number_1, number_2 ect.
    Can anybody tell me how.
    public String [] getFileList() {
    String [] f1;
    File f = new File(fpath);
    f1 = f.list();
    return f1;
    Best regards
    Soren

    Easy solution: change your naming scheme to be 2 or 3 digits (if possible)
    ie
    pic_01, pic_02 ... pic_09, pic_10
    Then the natural order of strings will take care of it for you.
    If you have more than 100 pics, you would have to do pic_001, pic_002... which would take you up to 1000.
    The not so easy solution:
    write your own java.util.Comparator to do the sorting.
    Heres an example, but it can easily break.
    It assumes that the format of the string is text_number and sorts accordingly.
    It will break if the strings don't end with _xxx
    Comparator picStringComparator = new Comparator() {
         public int compare(Object o1, Object o2) {
              String s1 = (String) o1;
              String s2 = (String) o2;
              int index = s1.lastIndexOf("_");
              String s1Prefix = s1.substring(0, index);
              int s1Number = Integer.parseInt(s1.substring(index + 1));
              index = s2.lastIndexOf("_");
              String s2Prefix = s2.substring(0, index);
              int s2Number = Integer.parseInt(s2.substring(index + 1));
              if (!s1Prefix.equals(s2Prefix)) {
                   return s1Prefix.compareTo(s2Prefix);
              else {
                   return s1Number > s2Number ? 1 : s1Number < s2Number ? -1 : 0;
    Arrays.sort(f1, picComparator);

  • 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);
    }

  • Newbie trying to sort 2D string array

    Dear all,
    After read some book chapters, web sites including this, I still don't get the point.
    If I have a file like,
    1 aaa 213 0.9
    3 cbb 514 0.1
    2 abc 219 1.3
    9 bbc 417 10.4
    8 dee 887 2.1
    9 bba 111 7.1
    and I load into memory as a String[][]
    here comes the problem, I sort by column 1 (aaa,...,bba) using an adaptation of the Quicksort algorithm for 2D arrays
    * Sort for a 2D String array
    * @param a an String 2D array
    * @param column column to be sort
    public static void sort(String[][] a, int column) throws Exception {
    QuickSort(a, 0, a.length - 1, column);
    /** Sort elements using QuickSort algorithm
    static void QuickSort(String[][] a, int lo0, int hi0, int column) throws Exception {
    int lo = lo0;
    int hi = hi0;
    int mid;
    String mitad;
    if ( hi0 > lo0) {
    /* Arbitrarily establishing partition element as the midpoint of
    * the array.
    mid = ( lo0 + hi0 ) / 2 ;
    mitad = a[mid][column];
    // loop through the array until indices cross
    while( lo <= hi ) {
    /* find the first element that is greater than or equal to
    * the partition element starting from the left Index.
    while( ( lo < hi0 ) && ( a[lo][column].compareTo(mitad)<0))
    ++lo;
    /* find an element that is smaller than or equal to
    * the partition element starting from the right Index.
    while( ( hi > lo0 ) && ( a[hi][column].compareTo(mitad)>0))
    --hi;
    // if the indexes have not crossed, swap
    if( lo <= hi )
    swap(a, lo, hi);
    ++lo;
    --hi;
    /* If the right index has not reached the left side of array
    * must now sort the left partition.
    if( lo0 < hi )
    QuickSort( a, lo0, hi, column );
    /* If the left index has not reached the right side of array
    * must now sort the right partition.
    if( lo < hi0 )
    QuickSort( a, lo, hi0, column );
    * swap 2D String column
    private static void swap(String[][] array, int k1, int k2){
    String[] temp = array[k1];
    array[k1] = array[k2];
    array[k2] = temp;
    ----- end of the code --------
    if I call this from the main module like this
    import MyUtil.*;
    public class kaka
    public static void main(String[] args) throws Exception
    String[][]a = MyUtil.fileToArray("array.txt");
    MyMatrix.printf(a);
    System.out.println("");
    MyMatrix.sort(a,1);
    MyMatrix.printf(a);
    System.out.println("");
    MyMatrix.sort(a,3);
    MyMatrix.printf(a);
    for the first sorting I get
    1 aaa 213 0.9
    2 abc 219 1.3
    9 bba 111 7.1
    9 bbc 417 10.4
    3 cbb 514 0.1
    8 dee 887 2.1
    (lexicographic)
    but for the second one (column 3) I get
    3 cbb 514 0.1
    1 aaa 213 0.9
    2 abc 219 1.3
    9 bbc 417 10.4
    8 dee 887 2.1
    9 bba 111 7.1
    this is not the order I want to apply to this sorting, I would like to create my own one. but or I can't or I don't know how to use a comparator on this case.
    I don't know if I am rediscovering the wheel with my (Sort String[][], but I think that has be an easy way to sort arrays of arrays better than this one.
    I've been trying to understand the Question of the week 106 (http://developer.java.sun.com/developer/qow/archive/106/) that sounds similar, and perfect for my case. But I don't know how to pass my arrays values to the class Fred().
    Any help will be deeply appreciated
    Thanks for your help and your attention
    Pedro

    public class StringArrayComparator implements Comparator {
      int sortColumn = 0;
      public int setSortColumn(c) { sortColumn = c; }
      public int compareTo(Object o1, Object o2) {
        if (o1 == null && o2 == null)
          return 0;
        if (o1 == null)
          return -1;
        if (o2 == null)
          return 1;
        String[] s1 = (String[])o1;
        String[] s2 = (String[])o2;
        // I assume the elements at position sortColumn is
        // not null nor out of bounds.
        return s1[sortColumn].compareTo(s2[sortColumn]);
    // Then you can use this to sort the 2D array:
    Comparator comparator = new StringArrayComparator();
    comparator.setSortColumn(0); // sort by first column
    String[][] array = ...
    Arrays.sort(array, comparator);I haven't tested the code, so there might be some compiler errors, or an error in the logic.

  • Help! Inserting a 1-D comment array into a 2-D string array at specified row AND column

    Hello everyone,
    I am writing a 2-D string array to excel and i need a way to add comments to my file like this:  
    SLAM    NAME    G Level    Comments
    1              RALF         26               
    1              RALF         26
    1              RALF         26
    1              RALF         26
    For some reason, i cannot specify a row AND column to write because: 
    When i use replace array subset it only replaces 1 element at my index. 
    When i use replace array subset with a loop, it creates empty spaces until it reaches the end of the array it is replacing.
    When i use Insert into array: i cannot wire 2 inputs for row and column.  
    In my complete VI i will need to write from row 1-1001, a different comment from 2-2002, a different comment from 3-3003, etc until a stop condition is met so i need to figure out how to do this programatically and not have it replace any elements outside of the range or it will override previous commetns. 
    I am at a loss of what to do. Any and all suggestions are greatly appreciated. 
    Thanks!
    Solved!
    Go to Solution.
    Attachments:
    array.vi ‏13 KB

    Hi proph,
    I made a small subtile change to yur VI and now it replaces all values of the 4th column…
    THINK DATAFLOW!
    Use shift registers when you need to propagate values from one loop iteration to the next!
    USE/LEARN DEBUGGING TECHNIQUES!
    There are tools like probes and highlight to understand your VI execution and to find problems…
    Go through all those free online courses offered by NI!
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome
    Attachments:
    array.vit ‏12 KB

  • Trying to setText on random JPanels via a String array?

    My assignment is to create a bunch of JButtons, and randomly have an "X" appear on one, until it is clicked, and then it goes away and reappears on another random one. It does this ten times and displays the time it took to do so.
    I've created all the JButtons, named b01 to b48 and put them in a gridLayout. That part works fine.
    I created a String[] array with the 48 names of the JButtons in it, then I was thinking I could go this route...
    Random r = new Random();
    String random = panels[r.nextInt(panels.length)];
    random.setText("X");  //This is where the program hangs up.I can replace the setText statement with a System.out.println statement, and it shows up on the console correctly...

    Brandon,
    Have a chook at my minesweeper game at http://forum.java.sun.com/thread.jspa?forumID=54&threadID=5248903 ... it uses a matrix of cells[rows][cols]... each Cell is a JPanel which contains a Button.
    I think you'll end up with something like ...
      // create an array of Buttons
      Button buttons[] = Button[NUM_BUTTONS];
      for (int i=0; i<NUM_BUTTONS; i++) {
        buttons[] = new Button(i);
      // Xify a random button for a random time
      buttons[random.nextInt(NUM_BUTTONS)].xify()I'd create a:
    class Button extends JButton
    * provides a constructor(int index) which sizes and places the button according to it's index
    * provides an "xify" method, which setText("X"), then sets-up a SwingTimer to setText(null) after a random time.
    Cheers. Keith.

  • 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

  • Returning String Array

    I'm trying to create a function (method?) for parsing some log files. The first index of the string array I want returned will contain a 'key' on what I'm doing with the log files (since they'll be formatted in several different ways depending on what's happening) and the rest will just return tokens from the logs. Here's what I have so far:
        public static String[] parseLog(String inString){
            StringTokenizer st = new StringTokenizer(inString, "\"<>");
            int stNum = st.countTokens();
            String[] parsedOut = new String[stNum + 1];
            if (inString.contains("disconnected")) {
                parsedOut[0] = "read";
            for (int x = 1; st.hasMoreTokens() ; x++){
                parsedOut[x] = st.nextToken().trim();
            return parsedOut;
        public static void main(String[] args) {
            String line = "????log L 08/15/2008 - 20:28:37: \"underTHEinfluence johnRAMBO<16><STEAM_0:0:204495><>\" disconnected";
            System.out.println("Parsed: " + parseLog(line));
        }{code}
    It compiles with no errors, but I'm getting this: Parsed: [Ljava.lang.String;@e09713
    Edited by: mr0ldie on Aug 16, 2008 1:37 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    prometheuzz wrote:
    A String representation of the array is given, while you want to display the individual items from the array.
    Try this:
    System.out.println(java.util.Arrays.toString(yourArray));
    Need closures - want to do mapchar(yourarray, System.out.println);
    :)

  • Dynamic string array

    I need to make a dynamic string array.
    Deeper explanation:
    I am trying to use a FOR loop to send a series of commands to an 8-channel device.  Each channel requires 7 (actually, 1/2 need only 5, the other 1/2 need 7) strings to set them up and the entire sequence needs to be performed 8 times.  I started a test .vi by simply using a constant array of type sting.  I can sequentially pick each string and program my device perfectly.  Now I'd like to do things like add the channel # somewhere in the mix, use variable values based on other controls in my .vi to set the parameters of the channel.
    EXAMPLE:
    The user sets certain values that determine delays and width for an 8-channel DDG (Digital Delay Generator, to some, a pulse generator).  These values then need to be loaded into the DDG.  The Strings will look something like this:
    ULSE1TATE 1
    ULSE1:WIDTH 0.009 000           *NOTEpaces behind decimal are for better viewability only
    ULSE1ELAY 0.000 000
    ULSE1YNC T0
    ULSE1:CMODE DUTY
    ULSE1COUNTER 1
    ULSE1:BCOUNTER 1
    ULSE2TATE 1
    ULSE2:WIDTH 0.000 300
    ULSE2ELAY 0.008 700
    ULSE2YNC T0
    ULSE2:CMODE NORMAL
    So widith and delay params change, the pulse# changes, and whether it's on certain channels decides if the mode is duty or normal and duty comes with the subsequent params pcount and bcount.
    help?
    PS - I am going to move the state, sync, and cmode to a common, initialize loop run only at program start, but I still need to use width, delay, and (variably) pcount and bcount.
    PPS - I am trying to edit post to diable smilies.  Commands should read:"colon, P (or D)" not ,
    PPPS - Success, at least for me.  I disabled smilies in my settings, I don't know if that means my posts won't show smilies or if just what I am looking at won't show smilies, any responders let me know how it's showing for you.
    Message Edited by Radiance_Jon on 07-16-2007 01:48 PM
    Message Edited by Radiance_Jon on 07-16-2007 01:52 PM

    smercurio_fc wrote:
    Well, in my experience I have found that dealing with errors early on is the best course of action as it leads to less headaches down the road...
    Auto-indexing is one of the more powerful features of LabVIEW. If you're familiar with text-based languages it's equivalent to the "foreach" statement. Basically it allows you to wire an array into a for-loop and the size of the array tells LabVIEW how many times the loop needs to execute. Inside the loop LabVIEW peels of each element of the array in order for each iteration of the loop. Looks like this:
    My comment regarding not needing the sequence frame was related to using the error cluster since that wire would allow you enforce data dependency like so:
    Note that the VISA resource wire does the same thing.
    "I got a little aggravated at how NI seemed to handle the loops in those two frames concurrently".  That's because LabVIEW is a data-flow language, and not a sequenced language like C or VB. In fact, that's one of the things that makes LabVIEW so powerful.
    Message Edited by smercurio_fc on 07-16-2007 04:48 PM
    MAN!  I KNEW that!!!!  GGRRRRR!!!  That makes sense.  Actually that's WHY I connected the error lines in the first place was to aide in flow control.  OH!!!  Still getting used to LabVIEW. 
    But I still have a question related to flow control.  Check out the pic below.  LabVIEW runs everything in a seemingly random order... well at least where it STARTS each chain of data.  It obviously starts with the static constants or the earliest data in each chain, but I can't figure out how in the world it's deciding WHICH chain to start first.  It kind of seems to go with the lower right and work it's way to top-left, but it doesn't exactly do that either.  I dunno if it's worth you answering this concern or not, but if you got one for me I'd be much obliged. 
    I should take a LabVIEW class!  Yeah right, as if they'd let me... R&D means I won't need it tomorrow ;( which stinks cause I'm liking LabVIEW the more I learn it.  (I was not fond of it in the beginning, but that was my stubborness). 
    thanks again so much for all your help!!!!
    Also, I am using all those strings to make my display appear as I want it to... I wonder if there is another way?  I am aware of system labels, but I like the look of the recessed, grayed control boxes better.
    Message Edited by Radiance_Jon on 07-16-2007 05:06 PM

  • 3D string array to file

    How can I write a 3D string array to file?

    sascha:
    You could do this a lot of different ways.
    The first and most obvious thing that comes to my mind is that you can
    think about a 3D array as an array of 2D arrays. (For that matter a
    2D array is an array of 1D arrays.)
    Thus you could use a for loop to index your 3D array down to 2D and
    then perform multiple writes to write each 2D array "element" of this
    array of 2D arrays to disk. You would probably want to write some
    sort of header which defines how many dimensions there are in the
    array so that whatever reads it back later will have an easier time
    reading it back. (Otherwise you'd have to implement EOF handling for
    the read back portion.)
    To read it back you just use the same logic but build a 3D array using
    a 2D read inside a for loop.
    Dou
    glas De Clue
    LabVIEW developer (looking for a job...
    [email protected]
    [email protected] (SaschaS) wrote in message news:...
    > How can I write a 3D string array to file?

  • Searching two dimensional string arrays

    Hello, I'm very new to Java. I would like some advice on the code below. What I'm trying to do is: I want the user to enter a 9 digit number which is already stored in an two dimensional array. The array is to be searched and the 9 digit number and corresponding name is to be printed and stored for future reference. Something is wrong with my array checking. If I enter the nine digit number, the program errors and asks me again for the number. If I enter 0-4, I receive an output. I just don't know how to compare string array values. Could someone please help me with this?
    import java.io.*;
    import java.util.*;
    public class SocialSn2
         public static void main(String args[]) throws Exception
              boolean validSSAN = false;
              Ssn(validSSAN);
              if (validSSAN)
                   //Ssn(false);//write the code here to continue processing
         }//end main
         public static void Ssn(boolean Validated)
              String[][] employees =
                   {{"333333333", "Jeff"},
                   {"222222222", "Keith"},
                   {"444444444", "Sally"},
                   {"555555555", "Kaylen"},
                   {"111111111", "Sheriden"}     };
              boolean found = false;
              while (!found)
                   System.out.println("Enter the employee's Social Security number.");
                   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                   try
                        String line = in.readLine();
                        int input = Integer.parseInt(line); //added
                        found = false;
                        for(int j = 0; j < 5; j++)
                        if(input >= 0 && input <= employees.length)
                             //if(employees[j][0].equals(input))
                                  //System.out.println(employees[input][0] + employees[input][1]);
                                  found = true;
                             System.out.println(employees[input][0] + " " + employees[input][1]);
                   catch (Exception exc)
                        System.out.println("error");
                        found = false;
              Validated = found;
         }//end Ssn
    }//end class

    There seems to be some problem with your loop for checking those values
    if you had used System.err.println() in your catch block you would see that you were getting an ArrayIndexOutOfBoundsException
    The following works for me.
    import java.io.*;
    import java.util.*;
    public class SocialSn2
    public static void main(String args[]) throws Exception
    boolean validSSAN = false;
    Ssn(validSSAN);
    if (validSSAN)
    //Ssn(false);//write the code here to continue processing
    }//end main
    public static void Ssn(boolean Validated)
    String[][] employees =
    {{"333333333", "Jeff"},
    {"222222222", "Keith"},
    {"444444444", "Sally"},
    {"555555555", "Kaylen"},
    {"111111111", "Sheriden"} };
    boolean found = false;
    System.out.println(employees.length);
    System.out.println(employees[0].length);
    while (!found)
    System.out.println("Enter the employee's Social Security number.");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    try
    String line = in.readLine();
    //int input = Integer.parseInt(line); //added
    found = false;
    for (int i=0; i< employees.length;i++)
         if(employees[0].equals(line))
         System.out.println(employees[i][0]+" "+employees[i][1]);
         found = true;
    catch (Exception exc)
    System.err.println(exc);
    found = false;
    Validated = found;
    }//end Ssn
    }//end class

  • .csv to a string array

    Hi,
    This is probably a simple problem, but I have a csv file with string values in one column and numbers in another.  For example:
    Volume,    6
    Diameter,  5
    But much larger of a file.
    I would like to be able to read the first column in and come up with an array of just the strings.  I have tried using the Read Text from file into the Spreadsheet string to Array into the Index Array functions, but I cannot seem to get this string array to work out, as it just comes up with 0's for any text.
    If anyone can point me in the right direction it would be greatly appreciated. 
    Thank You!!
    Solved!
    Go to Solution.

    Hi sean,
    you have to convert to an array of strings! Then you will receive your first column as text data...
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Concatenation of String array.

    Hello,
    I have two string array.
    String[] szTemp1={"abc", "d e f "};
    String[] szTemp2={"123", "4-5 6"};
    How can I make a concatenation to get an array with {"123", "4-5 6", "abc", "d e f"} !
    I tried String[] szTemp2={"123", "4-5 6"} + szTemp1; but this is not working!
    Thanks in advance.
    Alain.

    From the Java API, check:
    System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
    Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. The number of components copied is equal to the length argument. The components at positions srcPos through srcPos+length-1 in the source array are copied into positions destPos through destPos+length-1, respectively, of the destination array.
    If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.
    If dest is null, then a NullPointerException is thrown.
    If src is null, then a NullPointerException is thrown and the destination array is not modified.
    Otherwise, if any of the following is true, an ArrayStoreException is thrown and the destination is not modified:
    The src argument refers to an object that is not an array.
    The dest argument refers to an object that is not an array.
    The src argument and dest argument refer to arrays whose component types are different primitive types.
    The src argument refers to an array with a primitive component type and the dest argument refers to an array with a reference component type.
    The src argument refers to an array with a reference component type and the dest argument refers to an array with a primitive component type.
    Otherwise, if any of the following is true, an IndexOutOfBoundsException is thrown and the destination is not modified:
    The srcPos argument is negative.
    The destPos argument is negative.
    The length argument is negative.
    srcPos+length is greater than src.length, the length of the source array.
    destPos+length is greater than dest.length, the length of the destination array.
    Otherwise, if any actual component of the source array from position srcPos through srcPos+length-1 cannot be converted to the component type of the destination array by assignment conversion, an ArrayStoreException is thrown. In this case, let k be the smallest nonnegative integer less than length such that src[srcPos+k] cannot be converted to the component type of the destination array; when the exception is thrown, source array components from positions srcPos through srcPos+k-1 will already have been copied to destination array positions destPos through destPos+k-1 and no other positions of the destination array will have been modified. (Because of the restrictions already itemized, this paragraph effectively applies only to the situation where both arrays have component types that are reference types.)
    Parameters:
    src - the source array.
    srcPos - starting position in the source array.
    dest - the destination array.
    destPos - starting position in the destination data.
    length - the number of array elements to be copied.
    Throws:
    IndexOutOfBoundsException - if copying would cause access of data outside array bounds.
    ArrayStoreException - if an element in the src array could not be stored into the dest array because of a type mismatch.
    NullPointerException - if either src or dest is null.

Maybe you are looking for

  • Can I send a voice text that actually speaks to the person who receives it?

    Can Siri send a voice text that actually delivers the text in my voice??

  • Can't get Apple Remote to work

    Please help - I received my new Apple TV yesterday and have been trying to set up but cannot get the remote to work. Whatever I press there is no response from the status light. I have tried Menu and right for 6 secs to pair -> nothing. I've tried Me

  • External "Superdrive" not working with macbook?

    My macbook has a broken disk drive but I have a superdrive, how do i get it to work?  Computers with internal disk drives don't seem to like working with external ones.

  • USB 1.1 Port to USB 2.0 port?

    Is there a way I can upgrade my computer USB Ports to version 2.0? If so, where do I get the USB 2.0 controller card? I want to upgrade the actual USB 1.1 controller card which is in my computer to the version 2.0. Thanks for your time and help.

  • .avi files and 'ms' format audio

    Hi Folks, I have QuickTime 7 Pro and a .avi file I was sent (actually downloaded on FTP). I also have a host of other video players (MPlayer OS X 2, VLC, RealPlayer 10) All of them can play the .avi file but I get no audio. If I choose "Show movie pr