Example usage for java.lang Double parseDouble

List of usage examples for java.lang Double parseDouble

Introduction

In this page you can find the example usage for java.lang Double parseDouble.

Prototype

public static double parseDouble(String s) throws NumberFormatException 

Source Link

Document

Returns a new double initialized to the value represented by the specified String , as performed by the valueOf method of class Double .

Usage

From source file:Main.java

/**
 * For a string containing an unsigned number as judged by
 * <code>isUnsignedNumber()</code>, return the numerical value, rounded to
 * an integer./* w w w. jav  a2 s .c om*/
 *
 * @return the numeric value, rounded to an integer, or 0
 * if the string is not a valid unsigned number.
 */
public static int getUnsignedNumber(String string) {
    String s = string.trim();
    if (!isUnsignedNumber(s))
        return 0;
    double value = 0;
    try {
        value = Double.parseDouble(s);
    } catch (NumberFormatException e) {
        //logger.warn("Unexpected number value `" + s + "'");
    }
    return (int) Math.round(value);
}

From source file:Main.java

public static double parse(String str, double fallback) {
    try {/*w  w w . j  a v  a 2  s. c om*/
        return Double.parseDouble(str);
    } catch (NumberFormatException e) {
        return fallback;
    }
}

From source file:com.yhfudev.SimulatorForSelfStabilizing.java

public static void main(String[] args) {
    // command line lib: apache CLI http://commons.apache.org/proper/commons-cli/
    // command line arguments:
    //  -- input file
    //  -- output line to a csv file
    //  -- algorithm: Ding's linear or randomized

    // single thread parsing ...
    Options options = new Options();
    options.addOption("h", false, "print this message");
    //heuristic/*from   w ww.  jav a  2  s.  c  o  m*/
    options.addOption("u", false, "(rand) heuristic on");
    options.addOption("y", true, "show the graph with specified delay (ms)");
    options.addOption("i", true, "the input file name");
    options.addOption("o", true, "the results is save to a attachable output cvs file");
    options.addOption("l", true, "the graph activities trace log file name");
    options.addOption("s", true, "save the graph to a file");
    options.addOption("a", true, "the algorithm name, ding or rand");
    // options specified to generator
    options.addOption("g", true,
            "the graph generator algorithm name: fan1l, fan2l, rand, doro, flower, watt, lobster");
    options.addOption("n", true, "the number of nodes");
    options.addOption("d", true, "(rand) the node degree (max)");
    options.addOption("f", false, "(rand) if the degree value is fix or not");
    options.addOption("p", true, "(watt) the probability of beta");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        e.printStackTrace();
        return;
    }
    if (cmd.hasOption("h")) {
        showHelp(options);
        return;
    }

    int delay_time = 0;
    if (cmd.hasOption("y")) {
        delay_time = Integer.parseInt(cmd.getOptionValue("y"));
    }

    String sFileName = null;
    sFileName = null;
    FileWriter writer = null;
    if (cmd.hasOption("o")) {
        sFileName = cmd.getOptionValue("o");
    }
    if ((null != sFileName) && (!"".equals(sFileName))) {
        try {
            writer = new FileWriter(sFileName, true); // true: append
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Error: unable to open the output file " + sFileName);
            return;
        }
    }
    FileWriter wrGraph = null;
    sFileName = null;
    if (cmd.hasOption("s")) {
        sFileName = cmd.getOptionValue("s");
    }
    if ((null != sFileName) && (!"".equals(sFileName))) {
        try {
            wrGraph = new FileWriter(sFileName, true); // true: append
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Error: unable to open the saveGraph file " + sFileName);
            return;
        }
    }

    sFileName = null;
    if (cmd.hasOption("i")) {
        sFileName = cmd.getOptionValue("i");
    }
    String genname = null;
    if (cmd.hasOption("g")) {
        genname = cmd.getOptionValue("g");
    }
    if ((null == genname) && (null == sFileName)) {
        System.out.println("Error: not specify the input file or graph generator");
        showHelp(options);
        return;
    }
    if ((null != genname) && (null != sFileName)) {
        System.out.println("Error: do not specify the input file and graph generator at the same time");
        showHelp(options);
        return;
    }

    if (delay_time > 0) {
        // create and display a graph
        System.setProperty("org.graphstream.ui.renderer", "org.graphstream.ui.j2dviewer.J2DGraphRenderer");
    }

    Graph graph = new SingleGraph("test");
    //graph.setNullAttributesAreErrors(true); // to throw an exception instead of returning null (in getAttribute()).
    if (delay_time > 0) {
        graph.addAttribute("ui.quality");
        graph.addAttribute("ui.antialias");
        graph.addAttribute("ui.stylesheet", "url(data/selfstab-mwcds.css);");
        graph.display();
    }

    // save the trace to file
    FileSinkDGS dgs = null;
    if (cmd.hasOption("l")) {
        dgs = new FileSinkDGS();
        graph.addSink(dgs);
        try {
            dgs.begin(cmd.getOptionValue("l"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Generator generator = null;
    if (null != sFileName) {
        System.out.println("DEBUG: the input file=" + sFileName);
        FileSource source = new FileSourceDGS();
        source.addSink(graph);
        int count_edge_error = 0;
        try {
            //source.begin("data/selfstab-mwcds.dgs"); // Ding's paper example
            //source.begin("data/selfstab-ds.dgs");    // DS example
            //source.begin("data/selfstab-doro-1002.dgs"); // DorogovtsevMendes
            //source.begin("data/selfstab-rand-p10-10002.dgs"); // random connected graph with degree = 10% nodes
            //source.begin("data/selfstab-rand-f5-34.dgs"); // random connected graph with degree = 5
            source.begin(sFileName);
            while (true) {
                try {
                    if (false == source.nextEvents()) {
                        break;
                    }
                } catch (EdgeRejectedException e) {
                    // ignore
                    count_edge_error++;
                    System.out.println("DEBUG: adding edge error: " + e.toString());
                }
                if (delay_time > 0) {
                    delay(delay_time);
                }
            }
            source.end();
            //} catch (InterruptedException e) {
            //    e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("DEBUG: END read from source. # of edges ignored=" + count_edge_error);
    } else {
        // assert (genname != null);

        // graph generator
        //generator = new ChvatalGenerator(); // fix size
        //generator = new FullGenerator(); // full connected, 2 steps,1 node in dominate set
        //generator = new GridGenerator(); // only one result
        //generator = new HypercubeGenerator(); // one result
        //generator = new IncompleteGridGenerator(); // error
        //generator = new PetersenGraphGenerator(); // fix size
        //generator = new PointsOfInterestGenerator(); // error
        //generator = new RandomEuclideanGenerator(); // linear algo endless loop
        //generator = new RandomFixedDegreeDynamicGraphGenerator(); //
        //generator = new RandomGenerator(); //
        //generator = new URLGenerator("http://www.cnbeta.com"); //
        //generator = new WikipediaGenerator("Antarctica"); // no end

        //generator = new DorogovtsevMendesGenerator(); // ok
        //generator = new FlowerSnarkGenerator(); // ok
        //generator = new WattsStrogatzGenerator(maxSteps, 30, 0.5); // small world, ok
        //generator = new LobsterGenerator(); // tree like, ok

        int i;
        int n = 12; // the number of nodes
        if (cmd.hasOption("n")) {
            n = Integer.parseInt(cmd.getOptionValue("n"));
        }
        int d = 3; // the degree of nodes
        if (cmd.hasOption("d")) {
            d = Integer.parseInt(cmd.getOptionValue("d"));
        }
        boolean isFix = false;
        if (cmd.hasOption("f")) {
            isFix = true;
        }
        if ("".equals(genname)) {
            System.out.println("Error: not set generator name");
            return;
        } else if ("fan1l".equals(genname)) {
            generator = new FanGenerator();
        } else if ("fan2l".equals(genname)) {
            generator = new Fan2lGenerator(graph, d);
        } else if ("doro".equals(genname)) {
            generator = new DorogovtsevMendesGenerator();
        } else if ("flower".equals(genname)) {
            generator = new FlowerSnarkGenerator();
        } else if ("lobster".equals(genname)) {
            generator = new LobsterGenerator();
        } else if ("rand".equals(genname)) {
            generator = new ConnectionGenerator(graph, d, false, isFix);
        } else if ("watt".equals(genname)) {
            // WattsStrogatzGenerator(n,k,beta)
            // a ring of n nodes
            // each node is connected to its k nearest neighbours, k must be even
            // n >> k >> log(n) >> 1
            // beta being a probability it must be between 0 and 1.
            int k;
            double beta = 0.5;
            if (cmd.hasOption("p")) {
                beta = Double.parseDouble(cmd.getOptionValue("p"));
            }
            k = (n / 20) * 2;
            if (k < 2) {
                k = 2;
            }
            if (n < 2 * 6) {
                n = 2 * 6;
            }
            generator = new WattsStrogatzGenerator(n, k, beta);
        }
        /*int listf5[][] = {
        {12, 5},
        {34, 5},
        {102, 5},
        {318, 5},
        {1002, 5},
        {3164, 5},
        {10002, 5},
        };
        int listp3[][] = {
        {12, 2},
        {34, 2},
        {102, 3},
        {318, 9},
        {1002, 30},
        {3164, 90},
        {10002, 300},
        };
        int listp10[][] = {
        {12, 2},
        {34, 3},
        {102, 10},
        {318, 32},
        {1002, 100},
        {3164, 316},
        {10002, 1000},
        };
        i = 6;
        maxSteps = listf5[i][0];
        int degree = listf5[i][1];
        generator = new ConnectionGenerator(graph, degree, false, true);
        */
        generator.addSink(graph);
        generator.begin();
        for (i = 1; i < n; i++) {
            generator.nextEvents();
        }
        generator.end();
        delay(500);
    }

    if (cmd.hasOption("a")) {
        SinkAlgorithm algorithm = null;
        String algo = "rand";
        algo = cmd.getOptionValue("a");
        if ("ding".equals(algo)) {
            algorithm = new SelfStabilizingMWCDSLinear();
        } else if ("ds".equals(algo)) {
            algorithm = new SelfStabilizingDSLinear();
        } else {
            algorithm = new SelfStabilizingMWCDSRandom();
        }
        algorithm.init(graph);
        algorithm.setSource("0");
        if (delay_time > 0) {
            algorithm.setAnimationDelay(delay_time);
        }
        if (cmd.hasOption("u")) {
            algorithm.heuristicOn(true);
        } else {
            algorithm.heuristicOn(false);
        }
        algorithm.compute();

        GraphVerificator verificator = new MWCDSGraphVerificator();
        if (verificator.verify(graph)) {
            System.out.println("DEBUG: PASS MWCDSGraphVerificator verficiation.");
        } else {
            System.out.println("DEBUG: FAILED MWCDSGraphVerificator verficiation!");
        }

        if (null != writer) {
            AlgorithmResult result = algorithm.getResult();
            result.SaveTo(writer);
            try {
                writer.flush();
                writer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        algorithm.terminate();
    }

    if (null != generator) {
        generator.removeSink(graph);
    }
    if (dgs != null) {
        graph.removeSink(dgs);
        try {
            dgs.end();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (null != wrGraph) {
        try {
            saveGraph(graph, wrGraph);
            wrGraph.flush();
            wrGraph.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:io.github.jeddict.jcode.util.JavaUtil.java

public static double getJavaVersion() {
    return Double.parseDouble(ManagementFactory.getRuntimeMXBean().getSpecVersion());
}

From source file:Main.java

/**
 * For a string containing a semitones delta as judged by
 * <code>isSemitonesDelta()</code>, return the numerical value, as a
 * double./*from   w ww  .  j av  a 2 s  . c  om*/
 *
 * @return the numeric part of the semitones delta, or 0
 * if the string is not a valid semitones delta.
 */
public static double getSemitonesDelta(String string) {
    String s = string.trim();
    if (!isSemitonesDelta(s))
        return 0;
    String num = s.substring(0, s.length() - 2);
    double value = 0;
    try {
        value = Double.parseDouble(num);
    } catch (NumberFormatException e) {
        //logger.warn("Unexpected number value `" + num + "'");
    }
    return value;
}

From source file:Main.java

public static String getPrice(List<String> values) {
    String result = null;// ww w.  j  a  va2  s .  c  o m
    if (values != null) {
        if (values.size() == 1) {
            int index = values.get(0).indexOf(":");
            index = index + 1;
            if (index > 0 && index < values.get(0).length()) {
                result = values.get(0).substring(index);
                if (result.startsWith("-1")) {
                    result = null;
                } else {
                    result = "$" + result;
                }
            }
        } else if (values.size() > 1) {
            int index = 0;
            double max = 0.0;
            double min = -1.0;
            double tmp = 0.0;

            String strLow = null;
            String strHigh = null;

            for (String str : values) {
                index = str.indexOf(":");

                index = index + 1;
                if (index > 0 && index < str.length()) {
                    result = str.substring(index);
                    if (result.startsWith("-1")) {
                        result = null;
                    } else {
                        try {
                            tmp = Double.parseDouble(result);
                        } catch (Exception e) {

                        }

                        if (tmp > max) {
                            max = tmp;
                            strHigh = result;
                        }

                        if (min < 0 || tmp < min) {
                            min = tmp;
                            strLow = result;
                        }

                        if (strLow == null) {
                            strLow = result;
                        }
                    }
                }
            }

            result = "$" + strLow;
            if (strHigh != null) {
                result = result + "-" + strHigh;
            }

        }
    }
    return result;
}

From source file:Main.java

/**
 * Parses the supplied xsd:double string and returns its value.
 * /*from   ww w .j  a  v  a2s.c  om*/
 * @param s
 *        A string representation of an xsd:double value.
 * @return The <tt>double</tt> value represented by the supplied string argument.
 * @throws NumberFormatException
 *         If the supplied string is not a valid xsd:double value.
 */
public static double parseDouble(String s) {
    if (POSITIVE_INFINITY.equals(s)) {
        return Double.POSITIVE_INFINITY;
    } else if (NEGATIVE_INFINITY.equals(s)) {
        return Double.NEGATIVE_INFINITY;
    } else if (NaN.equals(s)) {
        return Double.NaN;
    } else {
        s = trimPlusSign(s);
        return Double.parseDouble(s);
    }
}

From source file:Main.java

/**
 * Add an entry to the database/*from  ww  w . j  a  va2 s . com*/
 *
 * @param db
 *            pointer to database
 * @param recordLine
 *            String with a record
 *            format: yy,mm,dd,hh:mm,light,solar,consumption
 *            e.g.: "15,08,13,13:54,35000,613.456,-120.22"
 */
public static void addDay(SQLiteDatabase db, String recordLine) {

    /* Parse the string into its single values */
    String[] valuesPerLine = recordLine.split(",");

    if (valuesPerLine.length == 1) {
        return;
    }
    /** String list with hour & minute values */
    String[] hourSplit = valuesPerLine[3].split(":");

    /** ContentValues to hold the measured and calculated values to be added to the database */
    ContentValues values = new ContentValues(14);
    values.put("year", Integer.parseInt(valuesPerLine[0]));
    values.put("month", Integer.parseInt(valuesPerLine[1]));
    values.put("day", Integer.parseInt(valuesPerLine[2]));
    values.put("hour", Integer.parseInt(hourSplit[0]));
    values.put("minute", Integer.parseInt(hourSplit[1]));
    values.put("solar", Double.parseDouble(valuesPerLine[5]));
    values.put("cons", Double.parseDouble(valuesPerLine[6]));
    values.put("light", Long.parseLong(valuesPerLine[4]));

    db.insert(TABLE_NAME, null, values);
}

From source file:Main.java

/**
 * For a string containing an unsigned semitones expression as judged by
 * <code>isUnsignedSemitones()</code>, return the numerical value as a
 * double.//from   w w  w  . j  a v  a  2s .  co  m
 *
 * @return the numeric part of the semitones expression, or 0 if the string
 * is not a valid unsigned semitones expression.
 */
public static double getUnsignedSemitones(String string) {
    String s = string.trim();
    if (!isUnsignedSemitones(s))
        return 0;
    String num = s.substring(0, s.length() - 2);
    double value = 0;
    try {
        value = Double.parseDouble(num);
    } catch (NumberFormatException e) {
        //logger.warn("Unexpected number value `" + num + "'");
    }
    return value;
}

From source file:Main.java

public static double parseCoordinate(CharSequence string) {
    int sign = 1;
    final Matcher negsignMatcher = PAT_NEGSIGN.matcher(string);
    if (negsignMatcher.find()) {
        sign = -1;/*from w  w  w . j  a v  a 2 s.  c  om*/
    }

    final Matcher signMatcher = PAT_SIGN.matcher(string);
    string = signMatcher.replaceAll("");

    final Matcher dmsMatcher = PAT_COORD_COMPONENT.matcher(string);
    double degrees = 0.0;
    for (double scale = 1.0; scale <= 3600.0 && dmsMatcher.find(); scale *= 60.0) {
        degrees += Double.parseDouble(dmsMatcher.group(1)) / scale;
    }
    return sign * degrees;
}