Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Use of Java to output non-zero values to Excel

  1. #1
    Junior Member
    Join Date
    Oct 2018
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Use of Java to output non-zero values to Excel

    Hi All,

    I have written a Java script which is coupled with an external Fluid Dynamics software package to output data to Excel. The data that is written to Excel is a temperature value (given as data[i] or the String q in my code below.

    The code that I have included below works well, except that it outputs unwanted zero temperature values to Excel. Is there a way of amending the code below to only output non-zero values of data[i] to Excel? I have tried doing things like adding in a line: data[i] = avReport.getValue() != 0, but this gives error values. I think the code within the /* Write data to file */ subsection needs amending to only give non-zero values, but I am unsure how to do this.

    Any help with this would be greatly appreciated.

    Thanks,
    James


    // STAR-CCM+ macro: Extract_1D_HeatFlux.java
    // Written by STAR-CCM+ 10.06.010
    package macro;
     
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.util.*;
     
    import star.common.*;
    import star.base.neo.*;
    import star.vis.*;
    import star.base.report.*;
    import star.meshing.*;
     
    public class Extract_1D_Temperature_Bed extends StarMacro {
     
        public void execute() {
            execute0();
        }
     
        private void execute0() {
     
    // User Defined Variables //
     
            String Bound = "Bed";
            String Reg = "Kiln";
            String Direction = "Z";
            int NumberOfDivisions = 50;
     
    // get range of direction on surface of interest
     
            double[] range = getRange(Direction, Bound, Reg);
     
    // get 1D data based in range and number of divisions
     
            double[] data = getData(range, NumberOfDivisions);
     
        }
     
    /* start of subroutine: getData */
     
        private double[] getData(double[] range, int NumberOfDivisions) {
     
            double[] data = new double[NumberOfDivisions];
     
            Simulation sim = getActiveSimulation();
     
    /* Get Threshold object */
            ThresholdPart thresh = (ThresholdPart) sim.getPartManager().getObject("1D_Threshold");
     
    /* Get Surface Average Report, associate threshold to it and set Boundary Heat Flux */
            AreaAverageReport avReport = (AreaAverageReport) sim.getReportManager().getReport("1D_Segment_Average");
     
            avReport.getParts().setObjects(thresh);
     
            PrimitiveFieldFunction temp = 
                ((PrimitiveFieldFunction) sim.getFieldFunctionManager().getFunction("Temperature"));
     
            avReport.setScalar(temp);
     
    /* Loop over the number of segments to compute the average */
            double SegmentLength = (range[1] - range[0]) / NumberOfDivisions;
     
    /* Open file to write data to */
            try {
                File f = new File(resolvePath("1D_Temperature_Bed.csv"));
                BufferedWriter bw = new BufferedWriter(new FileWriter(f));
                String Header = "Segment start coord, Segment end coord, Segment mid coord, Temperature";
                bw.write(Header);
                bw.newLine();
                bw.close();
            } catch (Exception e) {
                sim.println("Error unable to write data to file.");
            }
     
            for (int i = 0; i < NumberOfDivisions; i++) {
                /* Set threshold values */
                thresh.getRangeQuantities().setArray(new DoubleVector(new double[]{range[0] + 
                         (i * SegmentLength), range[0] + ((i + 1) * SegmentLength)}));
     
                /* get average value */
     
    data[i] = avReport.getValue();
                /* Pretty formatting for output */
                String Coord1 = String.format(Locale.UK, "%6.3f", Math.abs(range[0] + (i * SegmentLength)));
                String Coord2 = String.format(Locale.UK, "%6.3f", Math.abs(range[0] + ((i + 1) * SegmentLength)));
                String Coordm = String.format(Locale.UK, "%6.3f", Math.abs(range[0] + ((i + 0.5 ) * SegmentLength)));
                String q = String.format(Locale.UK, "%6.3f", data[i]);
     
                if (i == 0) {
                    sim.println("Start Coord, End Coord, Mid Coord Segment Average Temperature");
                }
                sim.println(Coord1 + ", " + Coord2 + ", " + Coordm + "," + q);
     
                /* Write data to file */
     
    try {
                    File f = new File(resolvePath("1D_Temperature_Bed.csv"));
                    BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
                    String line = Coord1 + ", " + Coord2 + ", " + Coordm + "," + q;
                    bw.write(line);
                    bw.newLine();
                    bw.close();
                } catch (Exception e) {
                    sim.println("Error unable to write data to file.");
                }
     
            }
     
            /* Tidy up objects used */
           /* sim.getReportManager().removeObjects(avReport);
            sim.getPartManager().removeObjects(thresh);*/
     
            return data;
        }
    /* End of subroutine getData */
     
    /* Start of subroutine getRange */
     
        private double[] getRange(String Direction, String Bound, String Reg) {
     
            double[] range = {0, 0};
            Simulation sim = getActiveSimulation();
     
            /* Create min, max and surface average report */
            MaxReport maxRep = sim.getReportManager().createReport(MaxReport.class);
            MinReport minRep = sim.getReportManager().createReport(MinReport.class);
            AreaAverageReport saRep = sim.getReportManager().createReport(AreaAverageReport.class);
            saRep.setPresentationName("1D_Segment_Average");
     
            /* Set Boundary Surface, i.e. Bed boundary as Parts */
            Boundary surf = sim.getRegionManager().getRegion(Reg).getBoundaryManager().getBoundary(Bound);
            maxRep.getParts().setObjects(surf);
            minRep.getParts().setObjects(surf);
     
            /* Units */
            Units units_0 = sim.getUnitsManager().getPreferredUnits(new IntVector(
                 new int[]{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}));
     
            /* Set Position as Sclar Field Function and set direction */
            PrimitiveFieldFunction primitiveFieldFunction_1 = 
                 ((PrimitiveFieldFunction) sim.getFieldFunctionManager().getFunction("Position"));
     
            if (Direction == "X") {
     
                VectorComponentFieldFunction component = 
                     ((VectorComponentFieldFunction) primitiveFieldFunction_1.getComponentFunction(0));
     
                ThresholdPart threshold = sim.getPartManager().createThresholdPart(new NeoObjectVector(new Object[]{surf}), 
                     new DoubleVector(new double[]{0.0, 1.0}), units_0, component, 0);
     
                threshold.setPresentationName("1D_Threshold");
     
                maxRep.setScalar(component);
                minRep.setScalar(component);
     
            } else if (Direction == "Y") {
     
                VectorComponentFieldFunction component = 
                     ((VectorComponentFieldFunction) primitiveFieldFunction_1.getComponentFunction(1));
     
                ThresholdPart threshold = sim.getPartManager().createThresholdPart(new NeoObjectVector(new Object[]{surf}), 
                     new DoubleVector(new double[]{0.0, 1.0}), units_0, component, 0);
     
                threshold.setPresentationName("1D_Threshold");
     
                maxRep.setScalar(component);
                minRep.setScalar(component);
     
            } else if (Direction == "Z") {
     
                VectorComponentFieldFunction component = 
                     ((VectorComponentFieldFunction) primitiveFieldFunction_1.getComponentFunction(2));
     
                ThresholdPart threshold = sim.getPartManager().createThresholdPart(new NeoObjectVector(new Object[]{surf}), 
                     new DoubleVector(new double[]{0.0, 1.0}), units_0, component, 0);
     
                threshold.setPresentationName("1D_Threshold");
     
                maxRep.setScalar(component);
                minRep.setScalar(component);
     
            } else {
                sim.println("Direction unknown - please check that you have specified X, Y or Z");
            }
     
            /* Get min and max values */
            range[0] = minRep.getReportMonitorValue();
            range[1] = maxRep.getReportMonitorValue();
     
            sim.println("Range of Boundary " + surf.getPresentationName() + 
                 " in " + Direction + " Direction is " + range[0] + "m to " + range[1] + "m.");
     
            /* delete reports */
            sim.getReportManager().removeObjects(minRep, maxRep);
     
            return range;
     
        }
    // End of subroutine getRange
    }
    // End of Main Program
    Last edited by Norm; October 19th, 2018 at 03:12 PM. Reason: Fixed code tags

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Use of Java to output non-zero values to Excel

    this gives error values.
    If you need help with error messages, please copy the full text of the error message and paste it here.
    The error message should include the source line.

    How close to zero do you want the double values that are to be ignored to be? Is there a lower range that you want to ignore? For example everything below 0.0000000001
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Oct 2018
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Use of Java to output non-zero values to Excel

    Quote Originally Posted by Norm View Post
    If you need help with error messages, please copy the full text of the error message and paste it here.
    The error message should include the source line.

    How close to zero do you want the double values that are to be ignored to be? Is there a lower range that you want to ignore? For example everything below 0.0000000001
    Hello,

    Thank you for your response. Anything lower than 0.00000000001 would be great. Any help with this would be fantastic.

    Thanks,
    James

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Use of Java to output non-zero values to Excel

    Have you tried using an if statement to skip the undesired values?
      if(value < 0.0000000001) 
           skip using value
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Oct 2018
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Use of Java to output non-zero values to Excel

    Quote Originally Posted by Norm View Post
    Have you tried using an if statement to skip the undesired values?
      if(value < 0.0000000001) 
           skip using value
    Hello,

    Thank you for your response. I have tried using your suggestion in my code, but get error values such as:
    error: ';' expected
           skip using data[i];
    and
    error: not a statement
           skip using data[i]
    ;. I have currently tried using your expression within the "write to file" part of my code - see code below. Where would you recommend that I add in the "skip" command to the code? As I only want to write non-zero values to Excel.

    Many thanks for your help.

    Code attempted:
    /* Write data to file */
     
    try {
                    File f = new File(resolvePath("1D_Temperature_Bed.csv"));
                    BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
                    String line = Coord1 + ", " + Coord2 + ", " + Coordm + "," + q;
    if(data[i] < 0.0000000001){ 
           skip using data[i];
    }
                    bw.write(line);
                    bw.newLine();
                    bw.close();
                } catch (Exception e) {
                    sim.println("Error unable to write data to file.");
                }
     
            }

  6. #6
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Use of Java to output non-zero values to Excel

    I'll answer for Norm since he isn't logged on now. You took him too literally. There is no "skip using" command. He was suggesting that you use an if statement to check for the precision and then add the appropriate logic to handle the situation.

    Regards,
    Jim

Similar Threads

  1. Convert string output to excel
    By kapamarou7 in forum Java Theory & Questions
    Replies: 3
    Last Post: January 29th, 2014, 02:57 PM
  2. Store data from Excel to Database without duplicate values
    By vector_ever in forum What's Wrong With My Code?
    Replies: 5
    Last Post: August 1st, 2013, 04:12 PM
  3. Replies: 2
    Last Post: July 9th, 2013, 09:51 PM
  4. Replies: 7
    Last Post: May 28th, 2013, 09:03 AM
  5. Replies: 2
    Last Post: July 7th, 2011, 03:46 PM

Tags for this Thread