Overwrite Array

Hello,
I have a problem I hope someone can help me
with. I am using LabView 4.1 to acquire data
from two serial ports. In order to make sure the
sequence of events happen correctly, I am using a
SEQUENCE Block. In pseudo code this is what I am
trying to accomplish:
Initialize 1D Array1 to 0
Write data to file
Initialize 1D Array2 to 0
Write data to file
Until user ends program {
Acquire data from serial port
Put data into 1D Array2
Write data to file
Subtract Array1 from Array2
Write result to file
Overwrite Array1 data with Array2 data
The problem I am having is with the last line
"Overwrite Array1 data with Array2 data". When I
wire Array2 back to Array1, I get a Wire Error
that says "Wire is a member of a cycle
I have tried putting the Array2 data into a dummy
array and then wiring the dummy array to Array1.
Same error.
I tried performing some additional math on the
dummy array and then wiring the dummy array to
Array1. Same error.
I have tried using the Index Element VI to create
another array by using the shift registers, and
then wiring to Array1. Same error.
In C this is a very simple operation. How can I
accomplish this in LabView? Any guidance is
appreciated.
Thanks in advance,
Brian Price
[email protected]
Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.

Brian,
Look at the attached graphic. I think this shows what you are trying to
acomplish
Jeffrey Benton
>In pseudo code this is what I am
>trying to accomplish:
>
>Initialize 1D Array1 to 0
>Write data to file
>Initialize 1D Array2 to 0
>Write data to file
>Until user ends program {
> Acquire data from serial port
> Put data into 1D Array2
> Write data to file
> Subtract Array1 from Array2
> Write result to file
> Overwrite Array1 data with Array2 data
>Thanks in advance,
>Brian Price
>[email protected]
>
[Attachment example.gif, see below]
Attachments:
example.gif ‏8 KB

Similar Messages

  • Writing multiple arrays to a single xml file at seperate times without overwriting the previous file?

    Hi my name is Dustin,
    I am new to labview and teststand... I am trying to right multiple arrays of data to a single xml file. I can do this with a cluster but I have to create a variable for each of those arrays (21 arrays) and I was hoping to use the same variable for each array. Meaning I obtain my array of data write it to an xml file then replace that array in that variable with a new array and then call up my VI that writes that array to an xml file and write it to the same xml file underneath the first array without overwriting it. Attached is my VI I created to write an array to an xml file. Again I am wondering if there is a way to write multiple arrays to a single xml file at different times without overwriting the previous xml file.
    Thanks
    Solved!
    Go to Solution.
    Attachments:
    Write_to_XML_File.vi ‏11 KB

    Hi dlovell,
    Check the attached example. I think it may help you.
    Regards,
    Nitz
    (Give Kudos to Good Answers, Mark it as a Solution if your problem is Solved) 
    Attachments:
    Write to XML.vi ‏17 KB

  • Array in object overwrite problem

    Hi
    hope you can help me with this as i've already been using too much time solving it myself :)
    I got a Board class which have an ArrayList<ArrayList<Integer>> as attribute. The Board class is controlled from my service class. I need to create a lot of boards which all needs different ArrayList<ArrayList<Integer>> input, so i made a for loop which creates the Boards. The problem is however when i change the variable i used to create the object the values also change inside the object even though the create method have already been called. English isn't my native language so it's a bit hard to explain :) Please ask if there's something you don't understand.
    thanks in advance!
    I made a temporary solution by making a 3d arraylist so i won't have to overwrite any values but thats not rly a good solution as it's starting to give me problems elsewhere.
    the method that creates the boards is Service.importCSV()
    model.Board
    package model;
    import java.util.ArrayList;
    public class Board {
         private String controleNumber;
         private ArrayList<ArrayList<Integer>> numbers = new ArrayList<ArrayList<Integer>>();
         private ArrayList<ArrayList<Integer>> remainingNumbers = new ArrayList<ArrayList<Integer>>();
         public Board(String controlenumber, ArrayList<ArrayList<Integer>> numbers) {
              this.controleNumber = controlenumber;
              this.numbers = numbers;
              this.remainingNumbers = numbers;
         public String getControlenumber() {
              return controleNumber;
         public void setControlenumber(String controleNumber) {
              this.controleNumber = controleNumber;
         public ArrayList<ArrayList<Integer>> getNumbers() {
              return numbers;
         public void setNumbers(ArrayList<ArrayList<Integer>> numbers) {
              this.numbers = numbers;
         public void setRemainingNumbers(ArrayList<ArrayList<Integer>> remainingNumbers) {
              this.remainingNumbers = remainingNumbers;
         public ArrayList<ArrayList<Integer>> getRemainingNumbers() {
              return remainingNumbers;
         public String toString() {
              return String.valueOf(controleNumber);
    }service.Service
    package service;
    import gui.MainFrame;
    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import ramdao.BoardDao;
    import model.Board;
    public class Service {
         private static ArrayList<Integer> numbers = new ArrayList<Integer>();
         public static List<Board> getAllBoards() {
              return BoardDao.getAllBoards();
         public static Board createBoard(String controleNumber, ArrayList<ArrayList<Integer>> numbers) {
              Board board = new Board(controleNumber, numbers);
              BoardDao.store(board);
              return board;
         public static void deleteBoard(Board board) {
              BoardDao.remove(board);
         public static Board checkFor(int checkFor) {
              for(Board board : getAllBoards()) {
                   System.out.println(board.getRemainingNumbers());
                   for(ArrayList<Integer> row : board.getRemainingNumbers()) {
                        for(int i=0;i<row.size();i++) {
                             if(numbers.contains(row.get(i))) {
                                  row.remove(row.get(i));
                   if(checkFor==1) {
                        for(ArrayList<Integer> row : board.getRemainingNumbers()) {
                             if(row.size()==0) {
                                  return board;
                   else if(checkFor==2) {
                        if(board.getRemainingNumbers().get(0).size()==0 && board.getRemainingNumbers().get(1).size()==0) {
                             return board;
                        else if(board.getRemainingNumbers().get(0).size()==0 && board.getRemainingNumbers().get(2).size()==0) {
                             return board;
                        else if(board.getRemainingNumbers().get(1).size()==0 && board.getRemainingNumbers().get(2).size()==0) {
                             return board;
                   else if(checkFor==3) {
                        if(board.getRemainingNumbers().size()==0) {
                             return board;
                   System.out.println(board.getRemainingNumbers()  );
              return null;
         public static ArrayList<Integer> oneToGo(int rows, ArrayList<Integer> numbers) {
              //TO-DO
              return null;
         public static void importCSV(ArrayList<String> buff) {
              ArrayList<ArrayList<ArrayList<Integer>>> allNumbers = new ArrayList<ArrayList<ArrayList<Integer>>>();
              int line = 0;
              String controleNumber = "";
              String[] splitLine = new String[10];
              for(int i=0;i<buff.size();i++) {
                   //adds the split buff to splitLine
                   for(int q=0;q<buff.get(i).split(";").length;q++) {
                        if(buff.get(i).split(";")[q].equals(""))
                             splitLine[q]="0";
                        else
                             splitLine[q]=buff.get(i).split(";")[q];
                   if(line==0) {
                        allNumbers.add(new ArrayList<ArrayList<Integer>>());
                        ArrayList<Integer> row = new ArrayList<Integer>();
                        allNumbers.get(allNumbers.size()-1).add(row);
                        controleNumber=buff.get(i).split(";")[0];
                        for(int q=buff.get(i).split(";").length;q<10;q++) {
                             splitLine[q]="0";
                        for(int q=0;q<9;q++) {
                             row.add(Integer.valueOf(splitLine[q+1]));
                   else if(line==1) {
                        ArrayList<Integer> row = new ArrayList<Integer>();
                        allNumbers.get(allNumbers.size()-1).add(row);
                        for(int q=buff.get(i).split(";").length;q<9;q++) {
                             splitLine[q]="0";
                        for(int q=0;q<9;q++) {
                             row.add(Integer.valueOf(splitLine[q]));
                   else if(line==2) {
                        ArrayList<Integer> row = new ArrayList<Integer>();
                        allNumbers.get(allNumbers.size()-1).add(row);
                        for(int q=buff.get(i).split(";").length;q<9;q++) {
                             splitLine[q]="0";
                        for(int q=0;q<9;q++) {
                             row.add(Integer.valueOf(splitLine[q]));
                        createBoard(controleNumber, allNumbers.get(allNumbers.size()-1));
                        line=-1;
                   line++;
         public static ArrayList<String> readFile(File file) {
              FileInputStream fileInputStream = null;
              ArrayList<String> buff = new ArrayList<String>();
              String line;
              try {
                   fileInputStream = new FileInputStream(file);
                   BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
                   BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));
                   while ((line = bufferedReader.readLine())!= null) {
                        buff.add(line);
              catch (IOException ex) {
                   Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
              finally {
                   try {
                        fileInputStream.close();
                   catch (IOException ex) {
                        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
              return buff;
         public static void addNumber(int number) {
              numbers.add(number);
         public static ArrayList<Integer> getNumbers() {
              return numbers;
    }

    Tried the code but it's full of compiletime errors. I changed it a little but still got
    Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problems:
         board cannot be resolved
         row cannot be resolved
         line cannot be resolved
         board cannot be resolved
         board cannot be resolvedwith the following code
    public static void importCSV(ArrayList<String> buff) {
              ArrayList<ArrayList<ArrayList<Integer>>> allNumbers
              = new ArrayList<ArrayList<ArrayList<Integer>>>();
              String[] splitLine = new String[10];
              String controleNumber;
              for(int i=0;i<buff.size();i++) {
                   int line = i % 3;
                   // split the buffer into fields
                   String[] splitBuf = buff.get(i).split(";");
                   int start = 0;
                   if(line==0) { // new board
                        ArrayList<ArrayList<Integer>> board = new ArrayList<ArrayList<Integer>>();
                        controleNumber = splitBuf[0];
                        start = 1;
                   ArrayList<Integer> row = new ArrayList<Integer>();
                   // fill row from the buffer fields...
                   for(int b = start, last = start+9; b < last; b++) {
                        if(b >= splitBuf.length || splitBuf.length() == 0)
                             row.add(0);
                        else
                             row.add(Integer.valueOf(splitBuf[b]));
              }This is my main problem:createBoard(controleNumber, board);
         board.clear();
         row.clear();The board that i created using the createBord method doesn't hold any numbers because i cleared the arrays i used to create it *after* creating it.
    got my software construction teacher to help me today :)
    works!     public static void importCSV(ArrayList<String> buff) {
              ArrayList<ArrayList<Integer>> board = new ArrayList<ArrayList<Integer>>();
              ArrayList<Integer> row = new ArrayList<Integer>();
              String controleNumber = "";
              int line;
              for(int i=0;i<buff.size();i++) {
                   line = i % 3;
                   String[] splitBuf = buff.get(i).split(";");
                   int start = 0;
                   if(line==0) { // new board
                        board = new ArrayList<ArrayList<Integer>>();
                        controleNumber = splitBuf[0];
                        start = 1;
                   row = new ArrayList<Integer>();
                   // fill row from the buffer fields...
                   for(int b = start, last = start+9; b < last; b++) {
                        if(b >= splitBuf.length || splitBuf[b].length() == 0)
                             row.add(0);
                        else
                             row.add(Integer.valueOf(splitBuf[b]));
                   board.add(row);
                   if(line==2) {
                        createBoard(controleNumber, board);
         }Edited by: Briam on Apr 12, 2010 12:37 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to overwrite an array?

    I am trying to overwrite the values in an array, but I am getting an ArrayIndexOutofBoundsException.
    This is how I am attempting to do it:
    if ((checkTempEnergy(tempDistance, numIons, Q)) < (checkEnergy(distance, numIons, Q))) {
         for (int i=0; i < numIons; i++) {
              arrayX[i] = tempX;
              arrayY[i] = tempY[i];
              arrayZ[i] = tempZ[i];
              distance[i] = tempDistance[i];
    The code compiles. Both arrays are the same size and declared the same way. The only difference is the name. Any help would be greatly appreciated, and I will award the 10 DUKE Stars.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    DrLaszloJamf wrote:
    You've been posting this question over and over and the drill should be familiar to you by now:
    1. Posting a snippet like that isn't really helpful to forum readers. For one thing, the fact that your code has such a trivial error in it makes you an unreliable reporter. Why should we believe what you claim?Ok, but the program is not complete, repeats itself, and looks awful. It is compilable though.
    public class FormingSalt2
         //creates a cube for the salt to form
         public static double volCube (double side) {
              double volume = side*side*side;
         return (volume);
         //create a random coordinates within the cube
         public static double randomCoord (double side) {
              double ranCoord = (double) (Math.random() * (side-3.76));
         return (ranCoord);
         //check the distances between ions but without double checking and without checking the distances between the same ions.
         public static double[] checkDistance (double arrayX[], double arrayY[], double arrayZ[], double distance[], int numIons) {
              //check the distances
              int l = 0;
              for (int i=1; i<numIons; i++) {
                   for (int j=0; j<i; j++){
                        double dx = arrayX[i] - arrayX[j];
                        double dy = arrayY[i] - arrayY[j];
                        double dz = arrayZ[i] - arrayZ[j];
                        distance[l] = Math.sqrt((dx*dx) + (dy*dy) + (dz*dz));
                        //System.out.println(tempDistance[l]+" is the distance "+ l);
                        l++;
         return distance;
         //check the temporary distances between the randomly moved ions but without double checking and without checking the distances between the same ions.
         public static double[] checkTempDistance (double tempX[], double tempY[], double tempZ[], double tempDistance[], int numIons) {
              //check the distances
              int l = 0;
              for (int i=1; i<numIons; i++) {
                   for (int j=0; j<i; j++){
                        double dx = tempX[i] - tempX[j];
                        double dy = tempY[i] - tempY[j];
                        double dz = tempZ[i] - tempZ[j];
                        tempDistance[l] = Math.sqrt((dx*dx) + (dy*dy) + (dz*dz));
                        //System.out.println(tempDistance[l]+" is the distance "+ l);
                        l++;
         return tempDistance;
         //checks the Total Energy between the ions
         public static double checkEnergy (double distance[], int numIons, double Q[]) {
              final double EPSILON = Math.sqrt(35.6*120), SIGMA = ((2.75+3.41)/2), K1 = 2.30, K2 = 0.0000552;
              double E1=0, E1sum=0, E2=0, E2sum=0;
              for (int i=1; i<numIons; i++) {     
                   for (int j=0; j<i; j++) {     
                        E1 = (K1) * ((Q[j]*Q)/distance[j]);
                        E1sum = E1sum + E1;
                        //System.out.println(E1);
                        E2 = (K2)*EPSILON* (Math.pow((SIGMA/distance[j]),12) - Math.pow((SIGMA/distance[j]),6));
                        E2sum = E2sum + E2;
                        //System.out.println(E2);
                        //System.out.println();
              //System.out.println(E1sum);
              //System.out.println();
              //System.out.println(E2sum);
              //System.out.println();
              double ETotal = (E1sum + E2sum) * Math.pow(10,-18);
         return ETotal;
         //checks the Total Temporary Energy between the randomly placed ions
         public static double checkTempEnergy (double tempDistance[], int numIons, double Q[]) {
              final double EPSILON = Math.sqrt(35.6*120), SIGMA = ((2.75+3.41)/2), K1 = 2.30, K2 = 0.0000552;
              double E1=0, E1sum=0, E2=0, E2sum=0;
              for (int i=1; i<numIons; i++) {     
                   for (int j=0; j<i; j++) {     
                        E1 = (K1) * ((Q[j]*Q[i])/tempDistance[j]);
                        E1sum = E1sum + E1;
                        //System.out.println(E1);
                        E2 = (K2)*EPSILON* (Math.pow((SIGMA/tempDistance[j]),12) - Math.pow((SIGMA/tempDistance[j]),6));
                        E2sum = E2sum + E2;
                        //System.out.println(E2);
                        //System.out.println();
              //System.out.println(E1sum);
              //System.out.println();
              //System.out.println(E2sum);
              //System.out.println();
              double ETotal = (E1sum + E2sum) * Math.pow(10,-18);
         return ETotal;
         //MAIN METHOD!
    public static void main(String[] args)
    double side=0;
    //Create the Cube and ask the user for how many Ions.
         //Number of Ions must be even for this program to converge/work.
         while (side<1.89){
              System.out.println("Choose length of one side of the Cube in Angstroms:");
              side = StdIn.readDouble();
              if (side<1.89){
              System.out.println("Side must be greater than Van der Waals radius of Argon, which is 1.88A.");
              System.out.println();
         System.out.println("The Volume of the Cube is: "+volCube(side));
         System.out.println();
         System.out.println("How many ions should there be in the Cube? Note: Odds are Na+ and Evens are Cl-");
         int numIons = StdIn.readInt();
         System.out.println();
         //Initialize and allocate memory for the Arrays...
         double arrayX[] = new double[numIons];
         double arrayY[] = new double[numIons];
         double arrayZ[] = new double[numIons];
         double tempX[] = new double[numIons];
         double tempY[] = new double[numIons];
         double tempZ[] = new double[numIons];
         int k=0;
         for (int j=1; j<numIons; j++){
              for (int i=0; i<j; i++) {
                   k++;
         double distance[] = new double[k];
         double tempDistance[] = new double[k];
         double Q[] = new double[numIons];
         for (int i=0; i<numIons; i++){
              Q[i] = Math.pow(-1, (i+2));
         //Creates the initial random set of (x,y,z) coordinates
         for (int i=0; i != numIons; i++) {
              arrayX[i] = randomCoord(side);
              arrayY[i] = randomCoord(side);
              arrayZ[i] = randomCoord(side);
              System.out.println("Coordinates for ion "+(i+1)+" are: ");
              System.out.println("("+ arrayX[i]+ ","+ arrayY[i]+","+ arrayZ[i]+")");
         //check the distances between the ions
         System.out.println();
         System.out.println("Distances are: ");
         checkDistance(arrayX, arrayY, arrayZ, distance, numIons);
         int l=0;
         for (int i=0; i<k; i++){
              System.out.println(distance[l]+" is the distance "+ l);
              l++;
         System.out.println();
         //check the energy between the ions in their initial position
         System.out.println(checkEnergy(distance, numIons, Q)+" is in Joules!");
         System.out.println();
         //ask the User how many Trials
         System.out.println("How many Trials?");
         int numTrials = StdIn.readInt();
         System.out.println();
         //Create a new random set of (x,y,z) coordinates by taking a random Step between -1.88 and 1.88 Angstroms
         for (int i=0; i<numIons; i++) {
              double tinyStepX = ((double)(Math.random()*(3.76))- 1.88); //adds a random step between -1.88 and 1.88 Angstroms
              double tinyStepY = ((double)(Math.random()*(3.76))- 1.88);
              double tinyStepZ = ((double)(Math.random()*(3.76))- 1.88);
              tempX[i] = arrayX[i] + tinyStepX;
              tempY[i] = arrayY[i] + tinyStepY;
              tempZ[i] = arrayZ[i] + tinyStepZ;
              System.out.println("Coordinates for ion "+(i+1)+" are: ");
              System.out.println("("+ tempX[i]+ ","+ tempY[i]+","+ tempZ[i]+")");
         //check the distances between the ions in the new positions
         System.out.println();
         System.out.println("Distances are: ");
         checkTempDistance(tempX, tempY, tempZ, tempDistance, numIons);
         l=0;
         for (int i=0; i<k; i++){
              System.out.println(tempDistance[l]+" is the distance "+ l);
              l++;
         System.out.println();
         //check the energy of the randomly moved ions
         System.out.println(checkTempEnergy(tempDistance, numIons, Q)+" is in Joules!");
         System.out.println();
         if ((checkTempEnergy(tempDistance, numIons, Q)) < (checkEnergy(distance, numIons, Q))) {
              for (int i=0; i < numIons; i++) {
                   arrayX[i] = tempX[i];
                   arrayY[i] = tempY[i];
                   arrayZ[i] = tempZ[i];
                   distance[i] = tempDistance[i];
         System.out.println(checkEnergy(distance, numIons, Q)+" is in Joules!");
         System.out.println();
    2. Once again, if you report an error you should indicate clearly the line that raises it. Once again you have failed to do this.Ok, my bad. The error is in line 200.
    3.. One day you will realize the best way to get help is to write a SSCCE: [http://mindprod.com/jgloss/sscce.html]
    My outputs are supposed to be random, so every output is different. But here is an example:
    [http://i285.photobucket.com/albums/ll52/RommelTJ/FormingSalt2_help.jpg|http://i285.photobucket.com/albums/ll52/RommelTJ/FormingSalt2_help.jpg]
    I am really sorry if I offended you or annoyed you in any way. I am just trying to get help and be nice. :(
    Edited by: RommelTJ on Jun 18, 2008 2:38 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Help: Problem With Seperate Arrays Overwriting Each Other!

    Hi,
    I have this function that randomly allocates free time to coursework blocks. This method works because I have tested numerous times and it always prints of different allocations of time every time its called.
    The problem that I have is that I have this method that called this method twice to store each different call within a separate ArrayList.
    When I make the first call the block are assigned to the array fine. But when I called it a second time to store the next result within a separate Array the first Array result are overwritten . Any body have any idea why this is happening, I have asked numerous friends and even my supervisor and he can't find anything wrong with it. Any help would be very helpful...
    Code:
    public ArrayList<CourseworkTimeBlock> courseworkAllocation(ArrayList timetable, ArrayList<CourseworkTimeBlock> cCourseworkBlocks){
              // Calculates and stores the free "time blocks" that can be used
              // to allocate coursework.
              ArrayList<Integer> freeTimeBlocks = new ArrayList<Integer>();
              freeTimeBlocks = freeBlocks(timetable);
              Random random = new Random();
              ArrayList<CourseworkTimeBlock> courseworkTimeBlocks = new ArrayList<CourseworkTimeBlock>();
              for(int i = 0; i < cCourseworkBlocks.size(); i++){
                   int allocateTo = -100;
                   int randomPoint = 0;
                   CourseworkTimeBlock courseworkBlock;
                   courseworkBlock = cCourseworkBlocks.get(i);
                   while(allocateTo < 0){
                        randomPoint = random.nextInt(freeTimeBlocks.size());
                        allocateTo = freeTimeBlocks.get(randomPoint);
                   courseworkBlock.setBlockAllocated(allocateTo);
                   courseworkTimeBlocks.add(courseworkBlock);
                   freeTimeBlocks.set(randomPoint, -1 );
              for( int i = 0; i < courseworkTimeBlocks.size(); i++){
                   System.out.println("CW: " + courseworkTimeBlocks.get(i).getBlockAllocated());
              return courseworkTimeBlocks;
         }These are the calls I make in a separate method:
    ArrayList<CourseworkTimeBlock> courseworkTimetableOne = new ArrayList<CourseworkTimeBlock>();
    ArrayList<CourseworkTimeBlock> courseworkTimetableTwo = new ArrayList<CourseworkTimeBlock>();
             courseworkTimetableOne = courseworkAllocation(fixedTimetable, courseworkBlocks);
             courseworkTimetableTwo = courseworkAllocation(fixedTimetable, courseworkBlocks);Edited by: ChrisUK on Mar 1, 2008 9:11 AM

    ChrisUK wrote:
    Thanks for the reply.
    In terms of the:
    courseworkTimetableOne = courseworkAllocation(fixedTimetable, courseworkBlocks);
    courseworkTimetableTwo = courseworkAllocation(fixedTimetable, courseworkBlocks);They are both supposed to pass in the fixedTimetable object, the reason being is that this is a timetable and is passed through in order to find it "free time" blocks.
    The courseworkTimetableOne and courseworkTimetableTwo are just different representations of how the coursework time blocks could be allocated to that given fixedtimetable. You're calling the same method with the same parameters, so both references are going to point to the same object. It's the same as if you just replaced the second line with courseworkTimetableTwo = courseworkTimetableOne.
    You've got two references pointing to the same object.
    The fact that you do this first:
    ArrayList<CourseworkTimeBlock> courseworkTimetableOne = new ArrayList<CourseworkTimeBlock>();
    ArrayList<CourseworkTimeBlock> courseworkTimetableTwo = new ArrayList<CourseworkTimeBlock>();means nothing. You create the two new ArrayLists, but then this
    courseworkTimetableOne = courseworkAllocation(fixedTimetable, courseworkBlocks);
    courseworkTimetableTwo = courseworkAllocation(fixedTimetable, courseworkBlocks);gets rid of them. The new ArrayLists you just created are lost.
    Remember when you assign to a reference variable such as courseworkTimetableOne =, all that does is copy a reference so now courseworkTimetableOne is pointing to the same object that whatever is on the RHS is pointing to.
    If you want two different lists, then either courseworkAllocation should make a copy of its internal list and return that, or else the caller should do it.
    >
    By the way what does "SSCCE" mean?[http://mindprod.com/jgloss/sscce.html|http://mindprod.com/jgloss/sscce.html]
    [http://homepage1.nifty.com/algafield/sscce.html|http://homepage1.nifty.com/algafield/sscce.html]

  • Last element in array is overwriting the entire array

    Hey all,
    Im a java student working on a homework assignment. My issue is:
    I have created two classes. One called Dependent and one called employee
    inside employee i have an array of dependents. The dependents class has methods called getfirstname()
    and getlastname();
    bascially im doing this.
    static Dependent[] Dependents = new Dependent[2];
    Dependents[0] = new Dependent("Ryan", "Karr");
    Dependents[1] = new Dependent("John", "Doe");
    Dependent[0].getFirstName(); // this returns john
    Dependent[1].getFirstName(); // this returns john aswell
    what am i doing wrong? If i take the static off dependents i get an error.
    im sorry if this is sketchy this is my first term taking java.
    my source is below
    Thank you!
    Ryan
    public class Employee
         static Dependant[] dependents;                                                       // Dependents Array
         static int numDependents = 0;                                             // Number of Dependents
         public Employee(int pNumDependents)
              dependents = new Dependant[pNumDependents];                         // Instanciate the dependents array
              String dFirstName;                                                       // Dependents First Name
              String dLastName;                                                       // Dependents Last Name
              Scanner input = new Scanner(System.in);                              // New input Scanner
              for(int i = 0; i < dependents.length; i++)
                   System.out.println("Dependent #" + (i+1));                    // A little bit of direction for the user
                   System.out.println("First Name: ");
                   dFirstName = input.nextLine();                                   // Dependents first name from user
                   System.out.println("Last Name: ");
                   dLastName = input.nextLine();                                   // Dependents last Name from user
                   addDependant(dFirstName, dLastName, this);                    // Add dependent call     
         public static void addDependant(String pFirstName, String pLastName, Employee employee)
                   // Make a new dependent
                   dependents[numDependents] = new Dependant(pFirstName, pLastName, employee);     
                   // Number of the dependent we're on plus one
                   numDependents++;
    }

    That was an example i made up. the error is with the code i posted, It doesnt through an error, it runs. However, when i do run it all the information inside is over written by the last value i entered.
    the code above was for addDependent which i call in the segment below, which obtains data from the user
              String dFirstName;                                                       // Dependents First Name
              String dLastName;                                                       // Dependents Last Name
              Scanner input = new Scanner(System.in);                              // New input Scanner
              for(int i = 0; i < dependents.length; i++)
                   System.out.println("Dependent #" + (i+1));                    // A little bit of direction for the user
                   System.out.println("First Name: ");
                   dFirstName = input.nextLine();                                   // Dependents first name from user
                   System.out.println("Last Name: ");
                   dLastName = input.nextLine();                                   // Dependents last Name from user
                   addDependant(dFirstName, dLastName, this);                    // Add dependent call     
              }

  • Lots of blank space when printing array with only last element printed

    I have a slight problem I have been trying to figure it out for days but can't see where my problem is, its probably staring me in the face but just can't seem to see it.
    I am trying to print out my 2 dimensional array outdie my try block. Inside the trying block I have two for loops in for the arrays. Within the second for loop I have a while to put token from Stringtokeniser into my 2 arrays. When I print my arrays in this while bit it prints fine however when I print outside the try block it only print the last element and lots of blank space before the element.
    Below is the code, hope you guys can see the problem. Thank you in advance
       import java.io.*;
       import java.net.*;
       import java.lang.*;
       import java.util.*;
       import javax.swing.*;
       public class javaflights4
          public static final String MESSAGE_SEPERATOR  = "#";
          public static final String MESSAGE_SEPERATOR1  = "*";
          public static void main(String[] args) throws IOException
             String data = null;
             File file;
             BufferedReader reader = null;
             file = new File("datafile.txt");
             String flights[] [];
                   //String flightdata[];
             flights = new String[21][7];
             int x = 0;
                   //flightdata = new String[7];
             int y = 0;
             try
                reader = new BufferedReader(new FileReader(file));   
                //data = reader.readLine();   
                while((data = reader.readLine())!= null)   
                   data.trim();
                   StringTokenizer tokenised = new StringTokenizer(data, MESSAGE_SEPERATOR1);
                   for(x = 0; x<=flights.length; x++)
                      for(y = 0; y<=flights.length; y++)
                         while(tokenised.hasMoreTokens())
                            //System.out.println(tokenised.nextToken());
                            flights [x] [y] = tokenised.nextToken();
                            //System.out.print("*"+ flights [x] [y]+"&");
                   System.out.println();
                catch(ArrayIndexOutOfBoundsException e1)
                   System.out.println("error at " + e1);
                catch(Exception e)
                finally
                   try
                      reader.close();
                      catch(Exception e)
             int i = 0;
             int j = 0;
             System.out.print(flights [j]);
    //System.out.println();

    A number of problems.
    First, I bet you see a lot of "error at" messages, don't you? You create a 21x7 array, then go through the first array up to 21, going through the second one all the way to 21 as well.
    your second for loop should go to flights[x].length, not flights.length. That will eliminate the need for ArrayIndexOutOfBounds checking, which should have been an indication that you were doing something wrong.
    Second, when you get to flights[0][0] (the very first iteration of the inner loop) you are taking every element from the StringTokenizer and setting flights[0][0] to each, thereby overwriting the previous one. There will be nothing in the StringTokenizer left for any of the other (21x7)-1=146 array elements. At the end of all the loops, the very first element in the array (flights[0][0]) should contain the last token in the file.
    At the end, you only print the first element (i=0, j=0, println(flight[ i][j])) which explains why you see the last element from the file.
    I'm assuming you have a file with 21 lines, each of which has 7 items on the line. Here is some pseudo-code to help you out:
    count the lines
    reset the file
    create a 2d array with the first dimension set to the number of lines.
    int i = 0;
    while (read a line) {
      Tokenize the line;
      count the tokens;
      create an array whose size is the number of tokens;
      stuff the tokens into the array;
      set flights[i++] to this array;
    }

  • How can I keep all the previous datas in the same array?

    I have a problem with keeping the previous datas in my array. The problem is when the iteration loop is executed, I have one or two value(s) stored in the array. The second iteration I have either one or two values (depending on the condition) coming out, but it overwrites my previous value. I want to keep all my data in the same array as the loop is executed.PS. I have attached a simple vi along this message. If anyone can help me out with this, I really appreciate for the help.
    Regards,
    Sonny

    If you iterate several times (N > 100) then I would suggest using the Initialize Array outside of the For Loop and then use the Replace Array Subset inside the Loop to populate the array. The reason for this is because the Build Array utility has to locate a new space in memory for the newly concatenated array -- the Replace Array Element utility uses the same memory space.
    If you iterate just a few times with a small array then using the Build Array should be okay.
    Chris_Mitchell
    Product Development Engineer
    Certified LabVIEW Architect

  • Saving array data from a waveform chart

    I am using a CRIO 9004 and a 9237 bridge module to measure some strains from strain gauges. I've got one timed loop that reads the DMA FIFO and puts the arrays of values (16 data points, 4 per channel) into a queue. In the consumer timed  loop a For loop scales the binary data, auto indexes it into arrays, then the arrays are merged into a 2D array for the four channels  displayed on a waveform chart . Everytime the consumer loop runs it indexes 4 data points (per channel) yet the waveform chart plots them in a consecutive manner and doesn't overwrite the previous four. If I convert the arrays to waveform arrays I don't see anything on the waveform chart.
    If I pass the 2D array of data to a array indicator inside or outside the consumer loop I get only 16 data points. I want to save the information that appears on the waveform chart  after the consumer loop but because I'm not using waveform data type I can't use the write waveforms to file vi. The waveform chart history buffer has been set to 195360.
    Idealy we will run the four channels for 120 seconds charting the data and saving the data. The minimum data rate is 1613kS/s (403 per channel) The data can be saved after the loops have finished gathering and processing or while they are running. I noticed when I tried to write to TDMS it slowed the consumer down. Same thing if I use a shift register with the volume of data.
    I suspect I'm not sending data to the chart in the correct manner ( usualy takes two attempts to "clear chart" using shortcut menu).  I'm not too familiar with timed loops /producer consumer loops  and just tried to put something together based on examples.
    I've attached my host vi and front panel screenshot.

    Hope they appear attached this time.
    Attachments:
    Basic DMA (Host).vi ‏444 KB
    screenshot2.jpg ‏113 KB

  • How to set the value of an array element (not the complete array) by using a reference?

    My situation is that I have an array of clusters on the front panel. Each element is used for a particular test setup, so if the array size is three, it means we have three identical test setups that can be used. The cluster contains two string controls and a button: 'device ID' string, 'start' button and 'status' string.
    In order to keep the diagrams simple, I would like to use a reference to the array as input into a subvi. This subvi will then modify a particular element in the array (i.e. set the 'status' string).
    The first problem I encounter is that I can not select an array element to write to by using the reference. I have tried setting the 'Selection s
    tart[]' and 'Selection size[]' properties and then querying the 'Array element' to get the proper element.
    If I do this, the VI always seems to write to the element which the user has selected (i.e. the element that contains the cursor) instead of the one I am trying to select. I also have not found any other possible use for the 'Selection' properties, so I wonder if I am doing something wrong.
    Of course I can use the 'value' property to get all elements, and then use the replace array element with an index value, but this defeats the purpose of leaving all other elements untouched.
    I had hoped to use this method specifically to avoid overwriting other array elements (such as happens with the replace array element) because the user might be modifying the second array element while I want to modify the first.
    My current solution is to split the array into two arrays: one control and one indicator (I guess that's really how it should be done ;-) but I'd still like to know ho
    w to change a single element in an array without affecting the others by using a reference in case I can use it elsewhere.

    > My situation is that I have an array of clusters on the front panel.
    > Each element is used for a particular test setup, so if the array size
    > is three, it means we have three identical test setups that can be
    > used. The cluster contains two string controls and a button: 'device
    > ID' string, 'start' button and 'status' string.
    >
    > In order to keep the diagrams simple, I would like to use a reference
    > to the array as input into a subvi. This subvi will then modify a
    > particular element in the array (i.e. set the 'status' string).
    >
    It isn't possible to get a reference to a particular element within an
    array. There is only one reference to the one control that represents
    all elements in the array.
    While it may seem better to use references to update
    an element within
    an array, it shouldn't really be necessary, and it can also lead to
    race conditions. If you write to an element that has the
    possibility of the user changing, whether you write with a local, a
    reference, or any other means, there is a race condition between the
    diagram and the user. LV will help with this to a certain extent,
    especially for controls that take awhile to edit like ones that use
    the keyboard. In these cases, if the user has already started entering
    text, it will not be overwritten by the new value unless the key focus
    is taken away from the control first. It is similar when moving a slider
    or other value changes using the mouse. LV will write to the other values,
    but will not rip the slider out of the user's hand.
    To completely avoid race conditions, you can split the array into user
    fields and indicators that are located underneath them. Or, if some
    controls act as both, you can do like Excel. You don't directly type
    into the cell. You choose w
    hich cell to edit, but you modify another
    location. When the edit is completed, it is incorporated into the
    display so that it is never lost.
    Greg McKaskle

  • IX4-300D how do I import a new drive into RAID 5 Array?

    I already had a 3 x 2TB RAID 5 array, added new forth drive (same 2TB drive model) and let it auto format, which completed OK, but when I look at Status in Admin I see "Unallocated 1.8TB". This tells me the drive was formated but not imported into the Array.
    Looking at Drive Management Page it shows all four drives installed but offers no actions, you cannot even select a drive to display or take action on.
    Going into Settings only shows the settings I used to create the RAID 5 initially, no other options. I would expect a workflow of right click new drive and select to import into RAID 5.
    Looking in the help section no detail on RAID only a basic comment on what RAID is.
    Something badly missing here. Is there some info I have missed?
    Peter

     Hello 2Old2Slow
    I highly recommend that you do make plans to backup your data from the unit before attempting to expand the RAID just in case something goes wrong in the process.  
    When trying to expand an existing RAID 5 from 3 to 4 disks, you can use the "add disks to storage system" option that is located in Drive Management>Settings.  This option will become available after a new drive is added to the empty drive and the unit is powered back on.  It may need to overwrite the new disk, it will indicate which disk is being overwritten by marking the new drive with green stripes.  If you are being asked to overwrite data but none of the disks show green stripes, please stop and backup first as proceeding will most likely result in all disks being overwritten. 
    LenovoEMC Contact Information is region specific. Please select the correct link then access the Contact Us at the top right:
    US and Canada: https://lenovo-na-en.custhelp.com/
    Latin America and Mexico: https://lenovo-la-es.custhelp.com/
    EU: https://lenovo-eu-en.custhelp.com/
    India/Asia Pacific: https://lenovo-ap-en.custhelp.com/
    http://support.lenovoemc.com/

  • Writing out to file - and it seems to overwrite data

    I have written a program that reads in a file and then writes out XML. It works fine with small files but with files that are 1,310 kb it, seems to overwrite itself and i end up with a file that is missing its begining and middle pieces. I suspect that I am blowing out some buffer and a java component is reseting itself and overwriting the file, but i am scratching my head. Code below, please excuse the unformatted nature of the code.
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.*;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class dl414image {
    public static String all = "";
    public static String fname = "";
    public static String lname = "";
    public static String mname = "";
    public static boolean aflag = false;
    public static boolean endofrec = false;
    public static boolean bflag = false;
    public static boolean cflag = false;
    public static boolean dflag = false;
    public static String xmldl;
    public static String xmlreq;
    public static String xml_issue_date;
    public static String xml_first_name;
    public static String xml_middle_name;
    public static String xml_last_name;
    public static String xml_dmvinfo;
    public static String xmlbday;
    public static String xmlsex;
    public static String xmlheight;
    public static String xmlweight;
    public static String xmleyecolor;
    public static String xmlhaircolor;
    public static String xml_licenseclass;
    public static String xml_licenseclassname;
    public static String xml_licenseissuedate;
    public static String xml_licenseexpiresdate;
    public static String dlstart = "<dlnumber>";
    public static String dlend = "</dlnumber>";
    public static String xmlreqstart = "<requestor_code>";
    public static String xmlreqend = "</requestor_code>";     
    public static String issue_date_start = "<issue_date>";
    public static String xml_issue_date_end = "</issue_date>";
    public static int count = 0;
    public static List<String> xml_abstractline = new ArrayList<String>();
    public static List<String> xml_cline = new ArrayList<String>();
    public static List<String> xml_dline = new ArrayList<String>();
    public static List<String> xml_acontinuedline = new ArrayList<String>();
    public static String dlold; // holds the previous DL number
    public static final String HEX_EXP = "[\\xFF]";
    public static final String CDATASTART = " <![CDATA[";
    public static final String CDATAEND = "]]>";
    public static String xmlfobates = "";
    public static String xmltypeappdate = "";
    public static String xml_licenseext;
    public static String xml_licenserestrict;
    public static String xml_licensedup;
    public static String xml_licenseheld;
    public static String xml_licenseseq;
    public static List<String> xml_abstract_item = new ArrayList<String>();
    public static List<String> xml_abstract_violationdate = new ArrayList<String>();
    public static List<String> xml_abstract_convictdate = new ArrayList<String>();
    public static List<String> xml_abstract_sectviolated = new ArrayList<String>();
    public static List<String> xml_abstract_statute = new ArrayList<String>();
    public static List<String> xml_abstract_file_number = new ArrayList<String>();
    public static List<String> xml_abstract_location_or_arn = new ArrayList<String>();
    public static List<String> xml_abstract_vehicle_license = new ArrayList<String>();
    public static final String ABST = "ABST";
    public static List<String> xml_reqNameAddress = new ArrayList<String>();
         /**<p>
         * This code reads in a file line by line
         * with BufferedReader and processes each
         * line.
         * @author Toren Valone
         public static void main(String[] args) {
              read("U:\\dlbig.txt"); //read this file
    //     convenience method to encapsulate
    //     the work of reading data.
         public static void read(String fileName) {
              xmlwriter("<?xml version=\"1.0\"?>");
              xmlwriter("<?xml-stylesheet type=\"text/xsl\" href=\"dl414.xsl\"?>" );
              xmlwriter("<dl_records>"); //write base element start tag
         try {
         BufferedReader in = new BufferedReader(
         new FileReader(fileName));
         String line;
         while ((line = in.readLine()) != null) {
              String cleanline = stripNonValidXMLCharacters(line);
         //our own method to do something
         handle(cleanline);
         //count each line
         count++;
         in.close();
         //show total at the end of file
         log("Lines read: " + count);
         } catch (IOException e) {
         log(e.getMessage());
         dlxmlwriter(); //final write for process
              xmlwriter("</dl_records>"); //write base element end tag
    //     does the work on every line as it is
    //     read in by our read method
         private static void handle(String line){
              if(line.length()> 0) {
              char fbyte = line.charAt(0);
              if(fbyte == 'A') {
              //just grab the very first dl
              if(count == 0) {
              dlold = line.substring(3,11);
              aflag = true;
              cflag = false;
              dflag = false;
              if(dlold.equalsIgnoreCase(line.substring(3,11))) {
              } else {
                   dlxmlwriter();
              //create Drivers License XML
                   xmldl = dlstart + line.substring(3,11) + dlend;
                   //grab f.o bates no only if its there otherwise write empty xml
              xmlfobates = "<fobates>" + line.substring(12,19) + "</fobates>";
              //grab type app and date
              xmltypeappdate = "<typeappdate>" + line.substring(20,28) + "</typeappdate>";
                   //Create Requestor code XML
              xmlreq = xmlreqstart + line.substring(51,56) + xmlreqend;
              //Create issue date XML
              xml_issue_date = issue_date_start + line.substring(57,63) + xml_issue_date_end;
              // clear name values, for now too stupid to figure out
              fname = "";
              mname = "";
              lname = "";     
              //Pulls the whole name string and sends it to namer function
              //to break up
              String name = line.substring(72);
              namer(name);
              //Create a string array and call get_Names which returns a
              //string array
              xml_first_name = "<first_name>" + fname + "</first_name>";
              xml_middle_name = "<middle_name>" + mname + "</middle_name>";
              xml_last_name = "<last_name>" + lname + "</last_name>";
                   //store Dl for comparison
                   store_old_dl(line);
              //Accent a and a length of 59 or 102 contains
              //the dmv info line
              if((fbyte == '?')& (line.length() == 59)){
                   String cleandmvinfo = regexReplacer(line.substring(38,58),"//","");
                   xml_dmvinfo = "<dmv_info_line>" + cleandmvinfo + "</dmv_info_line>";
              //Line length of 33 Birthdate, Sex, Height, Weight
              //Eye color hair color
              if ((line.length() == 33 ) & (aflag == true)) {
                   xmlbday = "<birth_date>" + line.substring(3, 9) + "</birth_date>";
                   xmlsex = "<sex>" + line.substring(11,12) + "</sex>";
                   xmlheight = "<height>" + line.substring(14,17) + "</height>";
                   xmlweight = "<weight>" + line.substring(18,21) + "</weight>";
                   xmleyecolor = "<eye_color>" + line.substring(22,27) + "</eye_color>";
                   xmlhaircolor = "<hair_color>" + line.substring(28,line.length()) + "</hair_color>";
    //Line length of 35 Birthdate, Sex, Height, Weight
              //Eye color hair color
              if ((line.length() == 31     ) & (aflag == true)) {
                   xmlbday = "<birth_date>" + line.substring(3, 9) + "</birth_date>";
                   xmlsex = "<sex>" + line.substring(11,12) + "</sex>";
                   xmlheight = "<height>" + line.substring(14,17) + "</height>";
                   xmlweight = "<weight>" + line.substring(18,21) + "</weight>";
                   xmleyecolor = "<eye_color>" + line.substring(22,27) + "</eye_color>";
                   xmlhaircolor = "<hair_color>" + line.substring(28,31) + "</hair_color>";
    // Line length of 56 Birthdate, Sex, Height, Weight
              //Eye color hair color for Annual reports
              if ((line.length() == 56     ) & (aflag == true)) {
                   xmlbday = "<birth_date>" + line.substring(3, 9) + "</birth_date>";
                   xmlsex = "<sex>" + line.substring(11,12) + "</sex>";
                   xmlheight = "<height>" + line.substring(14,17) + "</height>";
                   xmlweight = "<weight>" + line.substring(18,21) + "</weight>";
                   xmleyecolor = "<eye_color>" + line.substring(22,27) + "</eye_color>";
                   xmlhaircolor = "<hair_color>" + line.substring(28,31) + "</hair_color>";
              //If the line has an accent a and a length of 6
              if ((fbyte == '?')& (line.length() == 6)) {
              xml_licenseclass = "<license_class>" + line.substring(5,6) + "</license_class>";
              if ((fbyte == '?')& (line.length() == 8)) {
                   String cleanlc = regexReplacer(line.substring(4,8),"&","&");
                   xml_licenseclass = "<license_class>" + cleanlc + "</license_class>";
              if((line.length() == 61) & aflag==true) {
                   xml_licenseclassname = "<license_class_name>" + line.substring(3,9) + "</license_class_name>";
                   xml_licenseissuedate = "<license_issue_date>" + line.substring(9,16) + "</license_issue_date>";
                   xml_licenseexpiresdate = "<license_expires_date>" + line.substring(16,23) + "</license_expires_date>";
                   xml_licenseext = "<license_ext>" + line.substring(23,26) + "</license_ext>";
                   xml_licenserestrict = "<license_restrict>" + line.substring(26,37) + "</license_restrict>";          
                   xml_licensedup = "<license_dup>" + line.substring(38,43) + "</license_dup>";
                   xml_licenseheld = "<license_held>" + line.substring(44,44) + "</license_held>";
                   xml_licenseseq = "<license_seq>" + line.substring(57,61) + "</license_seq>";
              if(fbyte == 'B') {
                   bflag = true;
                   aflag = false; //ok got the a now turn switch off
                   String cleanabstract = regexReplacer(line.substring(1,line.length()),HEX_EXP,"");
                   cleanabstract = regexReplacer(cleanabstract,"&","&");
                   cleanabstract = regexReplacer(cleanabstract,"&","&apos;");
              if(cleanabstract.substring(3, 7).equalsIgnoreCase("ABST")){
                   if(cleanabstract.length() == 107) {               
                        xml_abstract_item.add("<abstract_item>" + cleanabstract.substring(3,8) + "</abstract_item>");
                   xml_abstract_violationdate.add("<abs_violation_date>" + cleanabstract.substring(8,14) + "</abs_violation_date>");
                   xml_abstract_convictdate.add("<abs_convict_date>" + cleanabstract.substring(15,21) + "</abs_convict_date>");
                   xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                   xml_abstract_statute.add("<abs_statute>" + cleanabstract.substring(42,46) + "</abs_statute>");
                   xml_abstract_file_number.add("<abs_file_number>" + cleanabstract.substring(67     ,79) + "</abs_file_number>");
                   xml_abstract_location_or_arn.add("<abs_location_or_arn>" + cleanabstract.substring(79,99) + "</abs_location_or_arn>");
                   xml_abstract_vehicle_license.add("<abs_vehicle_license>" + cleanabstract.substring(100,107) + "</abs_vehicle_license>");               
                   if(cleanabstract.length() > 80 & cleanabstract.length() < 107) {               
                        xml_abstract_item.add("<abstract_item>" + cleanabstract.substring(3,8) + "</abstract_item>");
                   xml_abstract_violationdate.add("<abs_violation_date>" + cleanabstract.substring(8,14) + "</abs_violation_date>");
                   xml_abstract_convictdate.add("<abs_convict_date>" + cleanabstract.substring(15,21) + "</abs_convict_date>");
                   xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                   xml_abstract_statute.add("<abs_statute>" + cleanabstract.substring(42,51) + "</abs_statute>");
                   xml_abstract_file_number.add("<abs_file_number>" + cleanabstract.substring(67     ,79) + "</abs_file_number>");
                   xml_abstract_location_or_arn.add("<abs_location_or_arn>" + cleanabstract.substring(79,cleanabstract.length()) + "</abs_location_or_arn>");
                   if(cleanabstract.length() < 80) {
                   System.out.println("****Change your assumtions about length*********");     
                        xml_abstractline.add("<abstract>" + cleanabstract + "</abstract>");
              if(cleanabstract.substring(3, 6).equalsIgnoreCase("ACC")){
                   if(cleanabstract.length() < 107) {
                        System.out.println("Acc looks like!!!" + cleanabstract);
                        System.out.println("Acc length=" + cleanabstract.length());
                   if(cleanabstract.length() > 102) {               
                             xml_abstract_item.add("<abstract_item>" + cleanabstract.substring(3,6) + "</abstract_item>");
                        xml_abstract_violationdate.add("<abs_violation_date>" + cleanabstract.substring(8,14) + "</abs_violation_date>");
                        xml_abstract_convictdate.add("<abs_convict_date>" + " " + "</abs_convict_date>");
                        xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                        xml_abstract_statute.add("<abs_statute>" + " " + "</abs_statute>");
                        xml_abstract_file_number.add("<abs_file_number>" + cleanabstract.substring(67     ,79) + "</abs_file_number>");
                        xml_abstract_location_or_arn.add("<abs_location_or_arn>" + cleanabstract.substring(79,99) + "</abs_location_or_arn>");
                        xml_abstract_vehicle_license.add("<abs_vehicle_license>" + cleanabstract.substring(100,cleanabstract.length()) + "</abs_vehicle_license>");               
                   if((cleanabstract.length() > 77 ) & cleanabstract.length() < 102) {               
                             xml_abstract_item.add("<abstract_item>" + cleanabstract.substring(3,6) + "</abstract_item>");
                        xml_abstract_violationdate.add("<abs_violation_date>" + cleanabstract.substring(8,14) + "</abs_violation_date>");
                        xml_abstract_convictdate.add("<abs_convict_date>" + " " + "</abs_convict_date>");
                        xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                        xml_abstract_statute.add("<abs_statute>" + " " + "</abs_statute>");
                        xml_abstract_file_number.add("<abs_file_number>" + cleanabstract.substring(67     ,cleanabstract.length()) + "</abs_file_number>");
                        xml_abstract_location_or_arn.add("<abs_location_or_arn>" + "</abs_location_or_arn>");
                        xml_abstract_vehicle_license.add("<abs_vehicle_license>" + "</abs_vehicle_license>");               
              if((fbyte == ' ') & (bflag == true)) {
                   String cleanabstract = regexReplacer(line.substring(1,line.length()),HEX_EXP,".");
                   cleanabstract = regexReplacer(cleanabstract,"&","&");
                   cleanabstract = regexReplacer(cleanabstract,"'","&apos;");
                   if(cleanabstract.substring(3, 7).equalsIgnoreCase("ABST")){
                             if(cleanabstract.length() == 107) {               
                                  xml_abstract_item.add("<abstract_item>" + cleanabstract.substring(3,8) + "</abstract_item>");
                             xml_abstract_violationdate.add("<abs_violation_date>" + cleanabstract.substring(8,14) + "</abs_violation_date>");
                             xml_abstract_convictdate.add("<abs_convict_date>" + cleanabstract.substring(15,21) + "</abs_convict_date>");
                             xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                             xml_abstract_statute.add("<abs_statute>" + cleanabstract.substring(42,51) + "</abs_statute>");
                             xml_abstract_file_number.add("<abs_file_number>" + cleanabstract.substring(67     ,79) + "</abs_file_number>");
                             xml_abstract_location_or_arn.add("<abs_location_or_arn>" + cleanabstract.substring(79,99) + "</abs_location_or_arn>");
                             xml_abstract_vehicle_license.add("<abs_vehicle_license>" + cleanabstract.substring(100,107) + "</abs_vehicle_license>");               
                             if(cleanabstract.length() > 93 & cleanabstract.length() < 107) {               
                                  xml_abstract_item.add("<abstract_item>" + cleanabstract.substring(3,8) + "</abstract_item>");
                             xml_abstract_violationdate.add("<abs_violation_date>" + cleanabstract.substring(8,14) + "</abs_violation_date>");
                             xml_abstract_convictdate.add("<abs_convict_date>" + cleanabstract.substring(15,21) + "</abs_convict_date>");
                             xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                             xml_abstract_statute.add("<abs_statute>" + cleanabstract.substring(42,51) + "</abs_statute>");
                             xml_abstract_file_number.add("<abs_file_number>" + cleanabstract.substring(67     ,79) + "</abs_file_number>");
                             xml_abstract_location_or_arn.add("<abs_location_or_arn>" + cleanabstract.substring(79,cleanabstract.length()) + "</abs_location_or_arn>");
                             xml_abstract_vehicle_license.add("<abs_vehicle_license>" + "</abs_vehicle_license>");               
                   if(cleanabstract.substring(3, 6).equalsIgnoreCase("ACC")){
                             if(cleanabstract.length() > 102) {               
                                       xml_abstract_item.add("<abstract_item>" + cleanabstract.substring(3,6) + "</abstract_item>");
                                  xml_abstract_violationdate.add("<abs_violation_date>" + cleanabstract.substring(8,14) + "</abs_violation_date>");
                                  xml_abstract_convictdate.add("<abs_convict_date>" + " " + "</abs_convict_date>");
                                  xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                                  xml_abstract_statute.add("<abs_statute>" + " " + "</abs_statute>");
                                  xml_abstract_file_number.add("<abs_file_number>" + cleanabstract.substring(67     ,79) + "</abs_file_number>");
                                  xml_abstract_location_or_arn.add("<abs_location_or_arn>" + cleanabstract.substring(79,99) + "</abs_location_or_arn>");
                                  xml_abstract_vehicle_license.add("<abs_vehicle_license>" + cleanabstract.substring(100,cleanabstract.length()) + "</abs_vehicle_license>");               
                             if((cleanabstract.length() > 77 ) & cleanabstract.length() < 102) {               
                                       xml_abstract_item.add("<abstract_item>" + cleanabstract.substring(3,6) + "</abstract_item>");
                                  xml_abstract_violationdate.add("<abs_violation_date>" + cleanabstract.substring(8,14) + "</abs_violation_date>");
                                  xml_abstract_convictdate.add("<abs_convict_date>" + " " + "</abs_convict_date>");
                                  xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                                  xml_abstract_statute.add("<abs_statute>" + " " + "</abs_statute>");
                                  xml_abstract_file_number.add("<abs_file_number>" + cleanabstract.substring(67     ,cleanabstract.length()) + "</abs_file_number>");
                                  xml_abstract_location_or_arn.add("<abs_location_or_arn>" + "</abs_location_or_arn>");
                                  xml_abstract_vehicle_license.add("<abs_vehicle_license>" + "</abs_vehicle_license>");               
                   if(cleanabstract.length() == 46) {
                   if(cleanabstract.substring(22, 25).equalsIgnoreCase("CDL") & cleanabstract.length() == 46) {
                   xml_abstract_item.add("<abstract_item>" + "</abstract_item>");
                        xml_abstract_violationdate.add("<abs_violation_date>" + "</abs_violation_date>");
                        xml_abstract_convictdate.add("<abs_convict_date>" + "</abs_convict_date>");
                        xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                        xml_abstract_statute.add("<abs_statute>" + cleanabstract.substring(42,cleanabstract.length()) + "</abs_statute>");
                        xml_abstract_file_number.add("<abs_file_number>" + "</abs_file_number>");
                        xml_abstract_location_or_arn.add("<abs_location_or_arn>" + "</abs_location_or_arn>");
                        xml_abstract_vehicle_license.add("<abs_vehicle_license>" + "</abs_vehicle_license>");               
                   if(cleanabstract.length()> 39 & cleanabstract.length() < 43     ) {
                   if(cleanabstract.substring(22, 25).equalsIgnoreCase("DMV")) {
                        System.out.println("DMV length=" + cleanabstract.length());
                        xml_abstract_item.add("<abstract_item>" + "</abstract_item>");
                        xml_abstract_violationdate.add("<abs_violation_date>" + "</abs_violation_date>");
                        xml_abstract_convictdate.add("<abs_convict_date>" + "</abs_convict_date>");
                        xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,cleanabstract.length()) + "</abs_section_violated>");
                        xml_abstract_statute.add("<abs_statute>" + "</abs_statute>");
                        xml_abstract_file_number.add("<abs_file_number>" + "</abs_file_number>");
                        xml_abstract_location_or_arn.add("<abs_location_or_arn>" + "</abs_location_or_arn>");
                        xml_abstract_vehicle_license.add("<abs_vehicle_license>" + "</abs_vehicle_license>");               
                   xml_abstractline.add("<abstract>" + cleanabstract + "</abstract>");
              if(fbyte == 'C') {
                   //turn b flag off
                   aflag = false;
                   bflag = false;
                   cflag = true;
                   String cleancomment = regexReplacer(line.substring(1,line.length()),HEX_EXP,"");     
                   cleancomment = regexReplacer(cleancomment,"&","&");
                   cleancomment = regexReplacer(cleancomment,"'","&apos;");
                   xml_cline.add("<comment_line>" + cleancomment.substring(1,63) + "</comment_line>");
                   xml_reqNameAddress.add("<requestor_name_or_address>" + cleancomment.substring(63,cleancomment.length()) + "</requestor_name_or_address>");
                   System.out.println("In C code dl=" + xmldl + "aflag=" + aflag +"bflag=" + bflag + "cflag=" + cflag);           
              if((fbyte == ' ') & (cflag == true)){
                   String cleancomment = regexReplacer(line.substring(1,line.length()),HEX_EXP,"");     
                   cleancomment = regexReplacer(cleancomment,"&","&");
                   if(cleancomment.length() > 63) {
              xml_reqNameAddress.add("<requestor_name_or_address>" + cleancomment.substring(63,cleancomment.length()) + "</requestor_name_or_address>");
              xml_cline.add("<comment_line>" + cleancomment.substring(1, 63) + "</comment_line>");
                   } else {
                        xml_cline.add("<comment_line>" + cleancomment.substring(1, cleancomment.length()) + "</comment_line>");
              if(fbyte == 'D') {
                   xml_dline.add("<action>" + line.substring(1, line.length()) + "</action>");
                   dflag = true;
                   cflag = false;
                   System.out.println("In d code dl=" + xmldl + "aflag=" + aflag +"bflag=" + bflag + "cflag=" + cflag + "dflag=" + dflag);
              } // ends d if
              //If D line sets it to true then this will never run
              if((fbyte == ' ') & (dflag == true)) {
                   xml_dline.add("<action>" + line.substring(1, line.length()) + "</action>");
              }     //end if line length greater than zero
         }// ends handle     
         public static void store_old_dl(String line) {
              dlold = line.substring(3,11);
         public static void dlxmlwriter(){
    xmlwriter("<dl_record>");
         xmlwriter(xmldl);
         xmlwriter(xmlfobates);
         xmlwriter(xmltypeappdate);
         xmlwriter(xmlreq);
         xmlwriter(xml_issue_date);
         xmlwriter(xml_first_name);
         xmlwriter(xml_middle_name);
         xmlwriter(xml_last_name);
         xmlwriter(xml_dmvinfo);
         xmlwriter(xmlbday);
         xmlwriter(xmlsex);
         xmlwriter(xmlheight);     
         xmlwriter(xmlweight);
         xmlwriter(xmleyecolor);
         xmlwriter(xmlhaircolor);
         xmlwriter(xml_licenseclass);
         xmlwriter(xml_licenseclassname);
         xmlwriter(xml_licenseissuedate);
         xmlwriter(xml_licenseexpiresdate);
         xmlwriter(xml_licenseext);
         xmlwriter(xml_licenserestrict);
         xmlwriter(xml_licensedup);
         xmlwriter(xml_licenseheld);
         xmlwriter(xml_licenseseq);
         int a = 0;
         while (a < xml_abstractline.size()) {
              xmlwriter(xml_abstractline.get(a).toString());
              a++;
         int a1 = 0;
         while (a1 < xml_abstract_item.size()) {
              xmlwriter(xml_abstract_item.get(a1).toString());
              a1++;
         int a2 = 0;
         while (a2 < xml_abstract_violationdate.size()) {
              xmlwriter(xml_abstract_violationdate.get(a2).toString());
              a2++;
         int a3 = 0;
         while (a3 < xml_abstract_convictdate.size()) {
              xmlwriter(xml_abstract_convictdate.get(a3).toString());
              a3++;
         int a4 = 0;
         while (a4 < xml_abstract_sectviolated.size()) {
              xmlwriter(xml_abstract_sectviolated.get(a4).toString());
              a4++;
         int a5 = 0;
         while (a5 < xml_abstract_statute.size()) {
              xmlwriter(xml_abstract_statute.get(a5).toString());
              a5++;
         int a6 = 0;
         while (a6 < xml_abstract_file_number.size()) {
              xmlwriter(xml_abstract_file_number.get(a6).toString());
              a6++;
         int a7 = 0;
         while (a7 < xml_abstract_location_or_arn.size()) {
              xmlwriter(xml_abstract_location_or_arn.get(a7).toString());
              a7++;
         int a8 = 0;
         while (a8 < xml_abstract_vehicle_license.size()) {
              xmlwriter(xml_abstract_vehicle_license.get(a8).toString());
              a8++;
         int d = 0;
         while (d < xml_cline.size()) {
              xmlwriter(xml_cline.get(d).toString());
              d++;
         int e = 0;
         while (e < xml_dline.size()) {
              xmlwriter(xml_dline.get(e).toString());
              e++;
         int f = 0;
         while (f < xml_reqNameAddress.size()) {
              xmlwriter(xml_reqNameAddress.get(f).toString());
              f++;
         dflag = false;
         //writes the entag for dlnumber and dl record
    xmlwriter("</dl_record>");
         xml_abstractline.clear();
         xml_cline.clear();
         xml_dline.clear();
         xml_abstract_item.clear();
         xml_abstract_violationdate.clear();
         xml_abstract_convictdate.clear();
         xml_abstract_sectviolated.clear();
         xml_abstract_statute.clear();
         xml_abstract_file_number.clear();
         xml_abstract_location_or_arn.clear();
         xml_abstract_vehicle_license.clear();
         xml_reqNameAddress.clear();
         public static void xmlwriter(String writestring){     
              String filename = "U:\\dl.xml";
                   try {
                        FileWriter myFW = new FileWriter(filename, true);
                        BufferedWriter out = new BufferedWriter(myFW);     
    out.flush();
                        out.write(writestring);
                        out.newLine();
                        out.close();
                   } catch (IOException f) {
                        System.out.println("Error -- " + f.toString());
                   }// ends catch
    //     convenience to save typing, keep focus
         private static

    Ok, here is the snippet that I think is having problems
    static void xmlwriter(String writestring){
    String filename = "U:dl.xml";
    try {
    FileWriter myFW = new FileWriter(filename, true);
    BufferedWriter out = new BufferedWriter(myFW);
    out.flush();
    out.write(writestring);
    out.newLine();
    out.close();
    } catch (IOException f) {
    System.out.println("Error -- " + f.toString());
    }// ends catch
    I call this for everyline written, and as I watch the file bytes count up, I then see it reset to zero and start over. Could this be something to do with creating a new buffer for every line?

  • Write arrays into a text file in different columns at different times

    Hi,
              I have a problem write data into a text file. I want to write 4 1D arrays into a text file. The problem is that I need to write it at different time and in different column (in other word, not only append the arrays).
    Do you have an idea to solve my problem?
    Thank you

    A file is long a linear string of data (text). In order ro insert columns, you need to rewrite the entire file, because colums are interlaced over the entire lenght of the file.
    So:
    read file into 2D array
    insert columns using array operations
    write resulting 2D array to file again.
    (Only if your colums are guaranteed to be fixed width AND you know the final number of colums, you could write the missing columns as spaces and then overwrite later. Still, it will be painful and inefficient, because column data are not adjacent in the file.)
    LabVIEW Champion . Do more with less code and in less time .

  • How to search for particular string in array?

    I am struggling to figure out how to search array contents for a string and then delete the entry from the array if it is found.
    The code for a program that allows the user to enter up to 20 inventory items (tools) is posted below; I apologize in advance for it as I am also not having much success grasping the concept of OOP and I am certain it is does not conform although it all compiles.
    Anyway, if you can provide some assistance as to how to go about searching the array I would be most grateful. Many thanks in advance..
    // ==========================================================
    // Tool class
    // Reads user input from keyboard and writes to text file a list of entered
    // inventory items (tools)
    // ==========================================================
    import java.io.*;
    import java.text.DecimalFormat;
    public class Tool
    private String name;
    private double totalCost;
    int units;
      // int record;
       double price;
    // Constructor for Tool
    public Tool(String toolName, int unitQty, double costPrice)
          name  = toolName;
          units = unitQty;
          price = costPrice;
       public static void main( String args[] ) throws Exception
          String file = "test.txt";
          String input;
          String item;
          String addItem;
          int choice = 0;
          int recordNum = 1;
          int qty;
          double price;
          boolean valid;
          String toolName = "";
          String itemQty = "";
          String itemCost = "";
          DecimalFormat fmt = new DecimalFormat("##0.00");
          // Display menu options
          System.out.println();
          System.out.println(" 1. ENTER item(s) into inventory");
          System.out.println(" 2. DELETE item(s) from inventory");
          System.out.println(" 3. DISPLAY item(s) in inventory");
          System.out.println();
          System.out.println(" 9. QUIT program");
          System.out.println();
          System.out.println("==================================================");
          System.out.println();
          // Declare and initialize keyboard input stream
          BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
          do
             valid = false;
             try
                System.out.print(" Enter an option > ");
                input = stdin.readLine();
                choice = Integer.parseInt(input);
                System.out.println();
                valid = true;
             catch(NumberFormatException exception)
                System.out.println();
                System.out.println(" Only numbers accepted. Try again.");
          while (!valid);
          while (choice != 1 && choice != 2 && choice != 9)
                System.out.println(" Not a valid option. Try again.");
                System.out.print(" Enter an option > ");
                input = stdin.readLine();
                choice = Integer.parseInt(input);
                System.out.println();
          if (choice == 1)
             // Declare and initialize input file
             FileWriter fileName = new FileWriter(file);
             BufferedWriter bufferedWriter = new BufferedWriter(fileName);
             PrintWriter dataFile = new PrintWriter(bufferedWriter);
             do
                addItem="Y";
                   System.out.print(" Enter item #" + recordNum + " name > ");
                   toolName = stdin.readLine();
                   if (toolName.length() > 15)
                      toolName = toolName.substring(0,15); // Convert to uppercase
                   toolName = toolName.toUpperCase();
                   dataFile.print (toolName + "\t");
                   do
                      valid = false;
                      try
                         // Prompt for item quantity
                         System.out.print(" Enter item #" + recordNum + " quantity > ");
                         itemQty = stdin.readLine();
                         // Parse integer as string
                         qty = Integer.parseInt (itemQty);
                         // Write item quantity to data file
                         dataFile.print(itemQty + "\t");
                         valid=true;
                      catch(NumberFormatException exception)
                         // Throw error for all non-integer input
                         System.out.println();
                         System.out.println(" Only whole numbers please. Try again.");
                   while (!valid);
                   do
                      valid = false;
                      try
                         // Prompt for item cost
                         System.out.print(" Enter item #" + recordNum + " cost (A$) > ");
                         itemCost = stdin.readLine();
                         // Parse float as string
                         price = Double.parseDouble(itemCost);
                         // Write item cost to data file
                         dataFile.println(fmt.format(price));
                         valid = true;
                      catch(NumberFormatException exception)
                         // Throw error for all non-number input (integers
                      // allowed)
                         System.out.println();
                         System.out.println(" Only numbers please. Try again.");
                   while (!valid);
                   // Prompt to add another item
                   System.out.println();
                   System.out.print(" Add another item? Y/N > ");
                   addItem = stdin.readLine();
                   while ((!addItem.equalsIgnoreCase("Y")) && (!addItem.equalsIgnoreCase("N")))
                      // Prompt for valid input if not Y or N
                      System.out.println();
                      System.out.println(" Not a valid option. Try again.");
                      System.out.print(" Add another item? Y/N > ");
                      addItem = stdin.readLine();
                      System.out.println();
                   // Increment record number by 1
                   recordNum++;
                   if (addItem.equalsIgnoreCase("N"))
                      System.out.println();
                      System.out.println(" The output file \"" + file + "\" has been saved.");
                      System.out.println();
                      System.out.println(" Quitting program.");
            while (addItem.equalsIgnoreCase("Y"));
    // Close input file
    dataFile.close();
       if (choice == 2)
       try {
          Read user input (array search string)
          Search array
          If match found, remove entry from array
          Confirm "deletion" and display new array contents
       catch block {
    } // class
    // ==========================================================
    // ListToolDetails class
    // Reads a text file into an array and displays contents as an inventory list
    // ==========================================================
    import java.io.*;
    import java.util.StringTokenizer;
    import java.text.DecimalFormat;
    public class ListToolDetails {
       // Declare variable
       private Tool[] toolArray; // Reference to an array of objects of type Tool
       private int toolCount;
       public static void main(String args[]) throws Exception {
          String line, name, file = "test.txt";
          int units, count = 0, record = 1;
          double price, total = 0;
          DecimalFormat fmt = new DecimalFormat("##0.00");
          final int MAX = 20;
          Tool[] items = new Tool[MAX];
          System.out.println("Inventory List");
          System.out.println();
          System.out.println("REC.#" + "\t" + "ITEM" + "\t" + "QTY" + "\t"
                + "PRICE" + "\t" + "TOTAL");
          System.out.println("\t" + "\t" + "\t" + "\t" + "PRICE");
          System.out.println();
          try {
             // Read a tab-delimited text file of inventory items
             FileReader fr = new FileReader(file);
             BufferedReader inFile = new BufferedReader(fr);
             StringTokenizer tokenizer;
             while ((line = inFile.readLine()) != null) {
                tokenizer = new StringTokenizer(line, "\t");
                name = tokenizer.nextToken();
                try {
                   units = Integer.parseInt(tokenizer.nextToken());
                   price = Double.parseDouble(tokenizer.nextToken());
                   items[count++] = new Tool(name, units, price);
                   total = units * price;
                } catch (NumberFormatException exception) {
                   System.out.println("Error in input. Line ignored:");
                   System.out.println(line);
                System.out.print(" " + count + "\t");
                System.out.print(line + "\t");
                System.out.print(fmt.format(total));
                System.out.println();
             inFile.close();
          } catch (FileNotFoundException exception) {
             System.out.println("The file " + file + " was not found.");
          } catch (IOException exception) {
             System.out.println(exception);
          System.out.println();
       //  Unfinished functionality for displaying "error" message if user tries to
       //  add more than 20 tools to inventory
       public void addTool(Tool maxtools) {
          if (toolCount < toolArray.length) {
             toolArray[toolCount] = maxtools;
             toolCount += 1;
          } else {
             System.out.print("Inventory is full. Cannot add new tools.");
       // This should search inventory by string and remove/overwrite matching
       // entry with null
       public Tool getTool(int index) {
          if (index < toolCount) {
             return toolArray[index];
          } else {
             System.out
                   .println("That tool does not exist at this index location.");
             return null;
    }  // classData file contents:
    TOOL 1     1     1.21
    TOOL 2     8     3.85
    TOOL 3     35     6.92

    Ok, so you have an array of Strings. And if the string you are searching for is in the array, you need to remove it from the array.
    Is that right?
    Can you use an ArrayList<String> instead of a String[ ]?
    To find it, you would just do:
    for (String item : myArray){
       if (item.equals(searchString){
          // remove the element. Not trivial for arrays, very easy for ArrayList
    }Heck, with an arraylist you might be able to do the following:
    arrayList.remove(arrayList.indexOf(searchString));[edit]
    the above assumes you are using 1.5
    uses generics and for each loop
    [edit2]
    and kinda won't work it you have to use an array since you will need the array index to be able to remove it. See the previous post for that, then set the value in that array index to null.
    Message was edited by:
    BaltimoreJohn

  • I have read 118 files (from a directory) each with 2088 data and put them into a 2 D array with 2cols and 246384row, I want to have aeach file on a separate columns with 2088 rows

    I have read 118 files from a directory using the list.vi. Each file has 2 cols with 2088rows. Now I have the data in a 2 D array with 2cols and 246384rows (118files * 2088rows). However I want to put each file in the same array but each file in separate columns. then I would have 236 columns (2cols for each of the 118 files) by 2088 rows. thank you very much in advance.

    Hiya,
    here's a couple of .vi's that might help out. I've taken a minimum manipulation approach by using replace array subset, and I'm not bothering to strip out the 1D array before inserting it. Instead I flip the array of filenames, and from this fill in the end 2-D array from the right, overwriting the column that will eventually become the "X" data values (same for each file) and appear on the right.
    The second .vi is a sub.vi I posted elsewhere on the discussion group to get the number of lines in a file. If you're sure that you know the number of data points is always going to be 2088, then replace this sub vi with a constant to speed up the program. (by about 2 seconds!)
    I've also updated the .vi to work as a sub.vi if you wa
    nt it to, complete with error handling.
    Hope this helps.
    S.
    // it takes almost no time to rate an answer
    Attachments:
    read_files_updated.vi ‏81 KB
    Num_Lines_in_File.vi ‏62 KB

Maybe you are looking for