Example usage for java.lang Float parseFloat

List of usage examples for java.lang Float parseFloat

Introduction

In this page you can find the example usage for java.lang Float parseFloat.

Prototype

public static float parseFloat(String s) throws NumberFormatException 

Source Link

Document

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

Usage

From source file:indexer.DocVector.java

public DocVector(String line, int numDimensions, int numIntervals) {
    String[] tokens = line.split("\\s+");
    this.docName = tokens[0];
    this.numDimensions = numDimensions;

    assert (tokens.length - 1 == numDimensions);
    x = new float[numDimensions];

    StringBuffer buff = new StringBuffer();
    for (int i = 1; i < tokens.length; i++) {
        x[i - 1] = Float.parseFloat(tokens[i]);
        buff.append(tokens[i]).append(" ");
    }//from   www  .j a  va2 s .  c o m
    DocVector.numIntervals = numIntervals;
    quantized = quantize();
}

From source file:net.sourceforge.processdash.ui.web.reports.PieChart.java

/** Create a  line chart. */
@Override//from  ww  w .  j a v a  2 s  .c o m
public JFreeChart createChart() {
    CategoryDataset catData = data.catDataSource();
    PieDataset pieData = null;
    if (catData.getColumnCount() == 1)
        pieData = DatasetUtilities.createPieDatasetForColumn(catData, 0);
    else
        pieData = DatasetUtilities.createPieDatasetForRow(catData, 0);

    JFreeChart chart = null;
    if (get3DSetting()) {
        chart = ChartFactory.createPieChart3D(null, pieData, true, true, false);
        chart.getPlot().setForegroundAlpha(ALPHA);
    } else {
        chart = ChartFactory.createPieChart(null, pieData, true, true, false);
    }

    PiePlot plot = (PiePlot) chart.getPlot();
    if (parameters.get("skipItemLabels") != null || parameters.get("skipWedgeLabels") != null)
        plot.setLabelGenerator(null);
    else if (parameters.get("wedgeLabelFontSize") != null)
        try {
            float fontSize = Float.parseFloat((String) parameters.get("wedgeLabelFontSize"));
            plot.setLabelFont(plot.getLabelFont().deriveFont(fontSize));
        } catch (Exception lfe) {
        }
    if (parameters.get("ellipse") != null)
        plot.setCircular(true);
    else
        plot.setCircular(false);

    Object colorScheme = parameters.get("colorScheme");
    if ("byPhase".equals(colorScheme))
        maybeConfigurePhaseColors(plot, pieData);
    else if ("consistent".equals(colorScheme))
        // since 2.0.9
        configureConsistentColors(plot, pieData);
    else if (parameters.containsKey("c1"))
        configureIndividualColors(plot, pieData);

    String interiorGap = (String) parameters.get("interiorGap");
    if (interiorGap != null)
        try {
            plot.setInteriorGap(Integer.parseInt(interiorGap) / 100.0);
        } catch (NumberFormatException e) {
        }
    String interiorSpacing = (String) parameters.get("interiorSpacing");
    if (interiorSpacing != null)
        try {
            plot.setInteriorGap(Integer.parseInt(interiorSpacing) / 200.0);
        } catch (NumberFormatException e) {
        }

    if (!parameters.containsKey("showZeroValues")) {
        plot.setIgnoreZeroValues(true);
        plot.setIgnoreNullValues(true);
    }

    return chart;
}

From source file:edu.snu.leader.hierarchy.simple.SimpleDistanceUpdateStrategy.java

/**
 * Initializes this update strategy//from w w  w.  j  a  v a  2s  .  co  m
 *
 * @param simState The simulation state
 * @see edu.snu.leader.hierarchy.simple.UpdateStrategy#initialize(edu.snu.leader.hierarchy.simple.SimulationState)
 */
@Override
public void initialize(SimulationState simState) {
    _LOG.trace("Entering initialize( simState )");

    // Get the simulation properties
    Properties props = simState.getProps();

    // Get the motivation increase due to time
    String motivationTimeIncrease = props.getProperty(_MOTIVATION_TIME_INCREASE_KEY);
    Validate.notEmpty(motivationTimeIncrease,
            "Motivation increase due to time is required (key=" + _MOTIVATION_TIME_INCREASE_KEY + ")");
    _motivationTimeIncrease = Float.parseFloat(motivationTimeIncrease);

    // Get the motivation increase due to neighbor activity
    String motivationNeighborIncrease = props.getProperty(_MOTIVATION_NEIGHBOR_INCREASE_KEY);
    Validate.notEmpty(motivationNeighborIncrease,
            "Motivation increase due to activity of a neighbor is required (key="
                    + _MOTIVATION_NEIGHBOR_INCREASE_KEY + ")");
    _motivationNeighborIncrease = Float.parseFloat(motivationNeighborIncrease);

    // Log the values
    _LOG.debug("_motivationTimeIncrease=[" + _motivationTimeIncrease + "] _motivationNeighborIncrease=["
            + _motivationNeighborIncrease + "]");

    _LOG.trace("Leaving initialize( simState )");
}

From source file:de.xaniox.heavyspleef.flag.presets.LocationFlag.java

@Override
public Location parseInput(SpleefPlayer player, String input) throws InputParseException {
    Location playerLocation = player.getBukkitPlayer().getLocation();

    double[] coords = new double[3];
    coords[0] = playerLocation.getX();/*  w ww .jav a 2  s  . co m*/
    coords[1] = playerLocation.getY();
    coords[2] = playerLocation.getZ();

    float yaw = playerLocation.getYaw();
    float pitch = playerLocation.getPitch();

    String[] args = input.split(" ");

    if (args.length >= 3) {
        for (int i = 0; i < 3; i++) {
            // Use ~ for a relative coordinate
            boolean relative = args[i].startsWith("~");
            if (relative) {
                args[i] = args[i].substring(1);
            }

            double result = 0;

            if (!args[i].isEmpty()) {
                try {
                    result = Double.parseDouble(args[i]);
                } catch (NumberFormatException nfe) {
                    throw new InputParseException(args[i], getI18N().getString(Messages.Player.NOT_A_NUMBER));
                }
            }

            if (relative) {
                coords[i] = coords[i] + result;
            } else {
                coords[i] = result;
            }
        }

        if (args.length > 3) {
            try {
                yaw = Float.parseFloat(args[3]);
            } catch (NumberFormatException nfe) {
                throw new InputParseException(args[3], getI18N().getString(Messages.Player.NOT_A_NUMBER));
            }

            if (args.length > 4) {
                try {
                    pitch = Float.parseFloat(args[4]);
                } catch (NumberFormatException nfe) {
                    throw new InputParseException(args[4], getI18N().getString(Messages.Player.NOT_A_NUMBER));
                }
            }
        }
    }

    return new Location(playerLocation.getWorld(), coords[0], coords[1], coords[2], yaw, pitch);
}

From source file:org.zilverline.web.SearchServiceValidator.java

/**
 * Validator for SearchForm. Validates name, maxResults, startAt and query
 * // w  w w .j  a v  a  2 s .co  m
 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
 */
public void validate(Object obj, Errors errors) {
    SearchServiceImpl service = (SearchServiceImpl) obj;
    int maxResults = service.getMaxResults();

    if (maxResults <= 0) {
        log.debug("Validation rejected for maxResults " + maxResults);
        errors.rejectValue("maxResults", "error.notapositivenumber", new Object[] { new Integer(maxResults) },
                "must be a positive number.");
    }

    BoostFactor factors = service.getFactors();
    Map mappings = factors.getFactors();
    // convert the keys to lowercase
    Iterator iter = mappings.entrySet().iterator();

    while (iter.hasNext()) {
        Map.Entry element = (Map.Entry) iter.next();
        String floatString = (String) element.getValue();
        log.debug("checking mappings: " + floatString);
        try {
            float f = Float.parseFloat(floatString);
        } catch (NumberFormatException e) {
            log.debug("value must be a float: " + floatString);
            errors.rejectValue("factors", null, null, "must be a float.");
        }
    }
}

From source file:org.apereo.lap.services.input.BaseInputHandler.java

public static Float parseFloat(String string, Float min, Float max, boolean cannotBeBlank, String name) {
    boolean blank = StringUtils.isBlank(string);
    if (cannotBeBlank && blank) {
        throw new IllegalArgumentException(name + " (" + string + ") cannot be blank");
    } else if (blank) {
        // can be blank, so return null
        return null;
    }//from   ww w .ja v a  2 s .  co  m
    Float num;
    try {
        num = Float.parseFloat(string);
        if (min != null && num < min) {
            throw new IllegalArgumentException(
                    name + " number (" + num + ") is less than the minimum (" + min + ")");
        } else if (max != null && num > max) {
            throw new IllegalArgumentException(
                    name + " number (" + num + ") is greater than the maximum (" + max + ")");
        }
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException(name + " (" + string + ") must be a float: " + e);
    }
    return num;
}

From source file:edu.uci.ics.fuzzyjoin.hadoop.recordpairs.MapBroadcastJoin.java

private void addJoinIndex(Path path) {
    try {//from w w  w .  j  av a  2 s  .c o m
        BufferedReader fis = new BufferedReader(new FileReader(path.toString()));
        String line = null;
        while ((line = fis.readLine()) != null) {
            String[] splits = line.split(" ");
            int ridR = Integer.parseInt(splits[0]);
            int ridS = Integer.parseInt(splits[1]);
            float similarity = Float.parseFloat(splits[2]);

            RIDPairSimilarity ridSimilarity = new RIDPairSimilarity(ridR, ridS, similarity);

            // Use ArrayList to lower the memory requirements. This causes
            // duplicated to be output. The duplicates need to be
            // eliminated in the Reduce.
            ArrayList<RIDPairSimilarity> ridSimilarities = joinIndexR.get(ridR);
            if (ridSimilarities != null) {
                ridSimilarities.add(ridSimilarity);
            } else {
                ridSimilarities = new ArrayList<RIDPairSimilarity>();
                ridSimilarities.add(ridSimilarity);
                joinIndexR.put(ridR, ridSimilarities);
            }

            ridSimilarities = joinIndexS.get(ridS);
            if (ridSimilarities != null) {
                ridSimilarities.add(ridSimilarity);
            } else {
                ridSimilarities = new ArrayList<RIDPairSimilarity>();
                ridSimilarities.add(ridSimilarity);
                joinIndexS.put(ridS, ridSimilarities);
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.alkacon.opencms.newsletter.CmsNewsletterSubscriberCleanupJob.java

/**
 * @see org.opencms.scheduler.I_CmsScheduledJob#launch(CmsObject, Map)
 *///from ww  w  . ja  va2 s .co m
public String launch(CmsObject cms, Map parameters) throws Exception {

    String maxAgeStr = (String) parameters.get(PARAM_MAXAGE);
    float maxAge;
    try {
        maxAge = Float.parseFloat(maxAgeStr);
    } catch (Exception e) {
        // in case of an error, use maxage of one week
        maxAge = 24f * 7f;
    }

    // calculate oldest possible date for the unconfirmed subscribers
    long expireDate = System.currentTimeMillis() - (long) (maxAge * 60f * 60f * 1000f);

    // now perform the image cache cleanup
    int count = removeInactiveSubscribers(cms, expireDate);

    return Messages.get().getBundle().key(Messages.LOG_NEWSLETTER_CLEANUP_FINISHED_COUNT_1, new Integer(count));
}

From source file:com.example.forum.TypeUtils.java

/**
 * float^?B/*from  ww  w  .j  a v  a  2s.c om*/
 * @param floatString ??B
 * @param defaultValue ftHgl?B
 * @return float^l?B
 */
public static float toFloat(String floatString, float defaultValue) {

    if (floatString == null || floatString.length() == 0) {
        return defaultValue;
    }

    float floatValue = defaultValue;
    try {
        floatValue = Float.parseFloat(floatString);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return floatValue;
}

From source file:com.seleniumtests.it.reporter.TestCustomReporter.java

/**
 * Check information are present in detailed report
 * @param testContext// w w  w  .  j  av a2  s.c om
 * @throws Exception
 */
@Test(groups = { "it" })
public void testDataInReport(ITestContext testContext) throws Exception {

    try {
        System.setProperty("customTestReports", "SUP::json::ti/report.test.vm");

        executeSubTest(1, new String[] { "com.seleniumtests.it.stubclasses.StubTestClass" },
                ParallelMode.METHODS, new String[] { "testAndSubActions", "testInError", "testWithException" });

        // check content of the file. It should contains all fields with a value
        String detailedReportContent = FileUtils
                .readFileToString(Paths.get(SeleniumTestsContextManager.getGlobalContext().getOutputDirectory(),
                        "testAndSubActions", "SUP-result.json").toFile());
        System.out.println(detailedReportContent);
        JSONObject json = new JSONObject(detailedReportContent);

        Assert.assertEquals(json.getInt("errors"), 0);
        Assert.assertEquals(json.getInt("failures"), 0);
        Assert.assertEquals(json.getString("hostname"), "");
        Assert.assertEquals(json.getString("suiteName"), "testAndSubActions");
        Assert.assertEquals(json.getString("className"), "com.seleniumtests.it.stubclasses.StubTestClass");
        Assert.assertEquals(json.getInt("tests"), 7);
        Assert.assertTrue(Float.parseFloat(json.get("duration").toString()) > 15);
        Assert.assertTrue(json.getLong("time") > 1518709523620L);
        Assert.assertEquals(json.getJSONArray("testSteps").length(), 7);
        Assert.assertEquals(json.getJSONArray("testSteps").get(3),
                "Step step 1\\nclick button\\nsendKeys to text field\\nStep step 1.3: open page\\nclick link\\na message\\nsendKeys to password field");
        Assert.assertEquals(json.getString("browser"), "NONE");
        Assert.assertNotNull(json.get("version"));
        Assert.assertTrue(json.getJSONObject("parameters").length() > 70);
        Assert.assertEquals(json.getJSONObject("parameters").getString("testType"), "NON_GUI");
        Assert.assertEquals(json.getJSONObject("parameters").getInt("replayTimeOut"), 30);
        Assert.assertEquals(json.getJSONArray("stacktrace").length(), 0);
    } finally {
        System.clearProperty("customTestReports");
    }
}