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:com.loadsensing.app.XarxaGMaps.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gmaps);//from  w w  w  .j  a va 2  s .c  o m

    MapController mapController;
    MapView mapa;

    // Obtenemos una referencia al control MapView
    mapa = (MapView) findViewById(R.id.mapa);

    // Mostramos los controles de zoom sobre el mapa
    mapa.setBuiltInZoomControls(true);

    // Aadimos la capa de marcadores
    List<Overlay> mapOverlays;
    Drawable drawable;
    OverlayXarxa itemizedOverlay;

    mapOverlays = mapa.getOverlays();
    drawable = this.getResources().getDrawable(R.drawable.marker);
    itemizedOverlay = new OverlayXarxa(drawable, mapa);

    int minLatitude = Integer.MAX_VALUE;
    int maxLatitude = Integer.MIN_VALUE;
    int minLongitude = Integer.MAX_VALUE;
    int maxLongitude = Integer.MIN_VALUE;

    SharedPreferences settings = getSharedPreferences("LoadSensingApp", Context.MODE_PRIVATE);
    String address = SERVER_HOST + "?session=" + settings.getString("session", "");
    Log.d(DEB_TAG, "Requesting to " + address);

    try {
        String jsonString = JsonClient.connectString(address);

        // Convertim la resposta string a un JSONArray
        JSONArray llistaXarxesArray = new JSONArray(jsonString);

        // HashMap<String, String> xarxa = null;

        for (int i = 0; i < llistaXarxesArray.length(); i++) {
            // xarxa = new HashMap<String, String>();
            JSONObject xarxaJSON = new JSONObject();
            xarxaJSON = llistaXarxesArray.getJSONObject(i);

            float lat = Float.parseFloat(xarxaJSON.getString("Lat"));
            float lon = Float.parseFloat(xarxaJSON.getString("Lon"));
            GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));

            int latInt = point.getLatitudeE6();
            int lonInt = point.getLongitudeE6();

            // Calculamos las coordenadas mximas y mnimas, para
            // posteriormente calcular el zoom y la posicin del mapa
            // centrado
            maxLatitude = Math.max(latInt, maxLatitude);
            minLatitude = Math.min(latInt, minLatitude);
            maxLongitude = Math.max(lonInt, maxLongitude);
            minLongitude = Math.min(lonInt, minLongitude);

            OverlayItem overlayitem = new OverlayItem(point,
                    xarxaJSON.getString("Nom") + " - " + xarxaJSON.getString("Sensors") + " sensors",
                    xarxaJSON.getString("Poblacio"));

            itemizedOverlay.addOverlay(overlayitem);
            mapOverlays.add(itemizedOverlay);
        }
        // setListAdapter(adapter);

    } catch (Exception e) {
        Log.d(DEB_TAG, "Error rebent xarxes");
    }

    // Definimos zoom y centramos el mapa
    mapController = mapa.getController();
    mapController.zoomToSpan(Math.abs(maxLatitude - minLatitude), Math.abs(maxLongitude - minLongitude));
    mapController.animateTo(new GeoPoint((maxLatitude + minLatitude) / 2, (maxLongitude + minLongitude) / 2));
}

From source file:game.com.AjaxUpdateGameServlet.java

private void handle(HttpServletRequest request, AjaxResponseEntity responseObject, DataAccess dataAccess)
        throws Exception {
    GsonBuilder gsonBuilder = new GsonBuilder().setDateFormat(AppConfig.dateFormat);
    Gson gson = gsonBuilder.create();//from ww w . j av  a2 s  .com
    String Id = Util.getParameter(request, "Id");
    if (StringUtils.isEmpty(Id)) {
        responseObject.returnMessage = "M s tuyn cp khng hp l";
        return;
    }
    String Ten = Util.getParameter(request, "Ten");
    if (StringUtils.isEmpty(Ten)) {
        responseObject.returnMessage = "Vui lng nhp tn tuyn cp";
        return;
    }
    String X1 = Util.getParameter(request, "X1");
    if (StringUtils.isEmpty(X1)) {
        responseObject.returnMessage = "Vui lng nhp t?a  X1";
        return;
    }
    String Y1 = Util.getParameter(request, "Y1");
    if (StringUtils.isEmpty(Y1)) {
        responseObject.returnMessage = "Vui lng nhp t?a  Y1";
        return;
    }
    String X2 = Util.getParameter(request, "X2");
    if (StringUtils.isEmpty(X2)) {
        responseObject.returnMessage = "Vui lng nhp t?a  X2";
        return;
    }
    String Y2 = Util.getParameter(request, "Y2");
    if (StringUtils.isEmpty(Y2)) {
        responseObject.returnMessage = "Vui lng nhp t?a  Y2";
        return;
    }

    float x1, y1, x2, y2;
    try {
        x1 = Float.parseFloat(X1);
    } catch (Exception ex) {
        responseObject.returnMessage = "T?a  X1 khng hp l";
        return;
    }
    try {
        y1 = Float.parseFloat(Y1);
    } catch (Exception ex) {
        responseObject.returnMessage = "T?a  Y1 khng hp l";
        return;
    }
    try {
        x2 = Float.parseFloat(X2);
    } catch (Exception ex) {
        responseObject.returnMessage = "T?a  X2 khng hp l";
        return;
    }
    try {
        y2 = Float.parseFloat(Y2);
    } catch (Exception ex) {
        responseObject.returnMessage = "T?a  Y2 khng hp l";
        return;
    }
    int id = 0;
    try {
        id = Integer.parseInt(Id);
        if (id < 1) {
            responseObject.returnMessage = "M s tuyn cp khng hp l";
            return;
        }
    } catch (Exception ex) {
        responseObject.returnMessage = "M s tuyn cp khng hp l";
        return;
    }
    //        TuyenCapEntity entity = new TuyenCapEntity();
    //        entity.Id = id;
    //        entity.Ten = Ten;
    //        entity.X1 = x1;
    //        entity.Y1 = y1;
    //        entity.X2 = x2;
    //        entity.Y2 = y2;
    //
    //       
    //        int row = dataAccess.updateTuyenCap(entity);
    //        if (row >= 0) {
    //            responseObject.data = entity.toJsonString();
    //            responseObject.returnCode = 1;
    //            responseObject.returnMessage = "Cp nht tuyn cp thnh cng";
    //        } else {
    //            responseObject.returnMessage = "Li h thng, vui lng th li sau";
    //        }

}

From source file:org.apereo.lap.controllers.ConfigController.java

@RequestMapping(value = "/config/save", method = RequestMethod.POST)
public @ResponseBody Response index(@RequestBody ConfigurationRequest model) {

    Response response = new Response();

    try {/*  www.  ja v a2 s.  c  o m*/
        if (!StringUtils.isNullOrEmpty(model.getSspRiskConfidenceThreshold())) {
            Double.parseDouble(model.getSspRiskConfidenceThreshold());
        }
    } catch (NumberFormatException e) {
        response.getErrors().add("Risk confidence threshold needs to be a number");
    }

    if (response.getErrors().size() == 0) {
        Configuration configuration = getConfiguration();
        configuration.setSspBaseUrl(model.getSspBaseUrl());
        if (!StringUtils.isNullOrEmpty(model.getSspRiskConfidenceThreshold())) {
            configuration
                    .setSSPRiskConfidenceThreshold(Float.parseFloat(model.getSspRiskConfidenceThreshold()));
        } else {
            configuration.setSSPRiskConfidenceThreshold(null);
        }
        configuration.setSSPActive(model.isSspActive());
        ;

        configurationRepository.save(configuration);
    }

    return response;
}

From source file:keel.Algorithms.Rule_Learning.C45Rules.C45.java

/** Constructor.
 *
 * @param paramFile The parameters file.
 *
 * @throws Exception If the algorithm cannot be executed.
 *///from  w w w.j av a2  s  . c  o m
public C45(parseParameters paramFile) throws Exception {
    try {

        // starts the time
        long startTime = System.currentTimeMillis();

        /* Sets the options of the execution from text file*/
        //StreamTokenizer tokenizer = new StreamTokenizer( new BufferedReader( new FileReader( paramFile ) ) );
        //initTokenizer( tokenizer) ;
        //setOptions( tokenizer );

        //File Names
        modelFileName = paramFile.getTrainingInputFile();
        trainFileName = paramFile.getValidationInputFile();
        testFileName = paramFile.getTestInputFile();
        //Options
        confidence = Float.parseFloat(paramFile.getParameter(1)); //confidence level for the uniform distribution
        minItemsets = Integer.parseInt(paramFile.getParameter(2)); //itemset per Leaf
        if (confidence < 0 || confidence > 1) {
            confidence = 0.25F;
            System.err.println("Error: Confidence must be in the interval [0,1]");
            System.err.println("Using default value: 0.25");
        }
        if (minItemsets <= 0) {
            minItemsets = 2;
            System.err.println("Error: itemsetPerLeaf must be greater than 0");
            System.err.println("Using default value: 2");
        }
        prune = false;

        /* Initializes the dataset. */
        modelDataset = new MyDataset(modelFileName, true);
        trainDataset = new MyDataset(trainFileName, false);
        testDataset = new MyDataset(testFileName, false);

        priorsProbabilities = new double[modelDataset.numClasses()];
        priorsProbabilities();
        marginCounts = new double[marginResolution + 1];

        // generate the tree
        generateTree(modelDataset);

    } catch (Exception e) {
        System.err.println(e.getMessage());
        System.exit(-1);
    }
}

From source file:com.owly.clnt.StatsWinTypeperf.java

public JSONObject getWinTypeperf() {

    String stat_val;

    char ch = '"';
    String st = "\\Memory\\Available bytes";
    String cmd = "typeperf  \"\\Memory\\Committed Bytes\" \"\\Memory\\Available Bytes\" \"\\processor(_total)\\% processor time\"  -sc 1";

    JSONObject genericstat = new JSONObject();
    JSONObject topCpujson = new JSONObject();
    String mydate;//www .  j  ava2 s .  c  o m
    String myserver;

    Logger log = Logger.getLogger(StatsWinTypeperf.class);

    try {

        log.debug("Initializating JSON object");

        mydate = this.getActualDate();
        myserver = this.getMyhost();

        genericstat.put("Host", myserver);
        genericstat.put("Date", mydate);
        genericstat.put("MetricType", "SystemStat");
        genericstat.put("StatType", "WinTypeperf");

        log.debug("Executing typeperf command");

        Process prc = Runtime.getRuntime().exec(cmd);

        BufferedReader buffread = new BufferedReader(new InputStreamReader(prc.getInputStream()));

        // read the child process' output
        String line;

        buffread.readLine();
        line = buffread.readLine();
        log.debug("Line readed = " + line);
        line = buffread.readLine();
        log.debug("Line readed = " + line);
        // Drop comma in the line readed
        String new_line = line.replace(",", " ");
        log.debug("New Line readed = " + new_line);

        // split based in the space
        String[] metric = new_line.trim().split("\\s+");

        for (int i = 2; i < metric.length; i++) {

            String value = metric[i];
            String value2 = value.replace("\"", " ");
            float fvalue;
            if ((i == 2) || (i == 3)) {
                fvalue = (Float.parseFloat(value2) / (1024 * 1024));
                log.debug("Value readed = " + fvalue);

            } else {
                fvalue = (Float.parseFloat(value2));
                log.debug("Value readed = " + fvalue);
            }
            topCpujson.put(stadistics[i - 2], fvalue);
            log.info("json stat value added :" + stadistics[i - 2] + ":" + fvalue);
        }

        buffread.close();

        log.debug("Adding metrics to Json Object");
        genericstat.put("Metrics", topCpujson);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return genericstat;

}

From source file:com.kysoft.cpsi.audit.service.SelfCheckServiceImpl.java

private Float parseFloat(String floatStr) {
    if (null != floatStr && !floatStr.trim().equals("")) {
        return Float.parseFloat(floatStr);
    } else {/*from   www  .  j  ava  2 s.  co m*/
        return Float.parseFloat("0.00");
    }
}

From source file:ddf.catalog.impl.operations.OverrideAttributesSupport.java

private static AttributeImpl overrideAttributeValue(AttributeDescriptor attributeDescriptor,
        Serializable overrideValue) {
    List<Serializable> newValue = new ArrayList<>();
    for (Object o : overrideValue instanceof List ? (List) overrideValue
            : Collections.singletonList(overrideValue)) {
        try {/*from ww  w .j  av  a2 s  .  com*/
            String override = String.valueOf(o);
            switch (attributeDescriptor.getType().getAttributeFormat()) {
            case INTEGER:
                newValue.add(Integer.parseInt(override));
                break;
            case FLOAT:
                newValue.add(Float.parseFloat(override));
                break;
            case DOUBLE:
                newValue.add(Double.parseDouble(override));
                break;
            case SHORT:
                newValue.add(Short.parseShort(override));
                break;
            case LONG:
                newValue.add(Long.parseLong(override));
                break;
            case DATE:
                Calendar calendar = DatatypeConverter.parseDateTime(override);
                newValue.add(calendar.getTime());
                break;
            case BOOLEAN:
                newValue.add(Boolean.parseBoolean(override));
                break;
            case BINARY:
                newValue.add(override.getBytes(Charset.forName("UTF-8")));
                break;
            case OBJECT:
            case STRING:
            case GEOMETRY:
            case XML:
                newValue.add(override);
                break;
            }
        } catch (IllegalArgumentException e) {
            return null;
        }
    }
    return new AttributeImpl(attributeDescriptor.getName(), newValue);
}

From source file:com.axiomine.largecollections.util.LargeCollection.java

protected void initializeBloomFilter() {
    this.myFunnel = new Funnel() {
        public void funnel(Object obj, PrimitiveSink into) {
            into.putInt(obj.hashCode());
        }//from ww w. j  a v a 2  s .  co m
    };
    float defaultFalsePositives = 0.03f;
    if (!StringUtils.isBlank(System.getProperty(LargeCollection.OVERRIDE_BF_FPP))) {
        String fpp = System.getProperty(LargeCollection.OVERRIDE_BF_FPP);
        try {
            float f = Float.parseFloat(fpp);
            if (f <= 0 || f > 0.2) {
                throw new RuntimeException(
                        "Bloom filter false postives probability range should be between 0 (excluded) and 0.2 (included), provided value = "
                                + f);
            } else {
                defaultFalsePositives = f;
            }
        } catch (Exception ex) {
            throw Throwables.propagate(ex);
        }
    }
    this.bloomFilter = BloomFilter.create(myFunnel, this.bloomFilterSize, defaultFalsePositives);
}

From source file:alba.solr.core.DynamicValueSourceParser.java

@SuppressWarnings("unchecked")
public ValueSource parse(FunctionQParser fp) throws SyntaxError {

    String functionName;//from  w  w  w. ja  v a 2 s  .c om

    List<ValueSource> valueSourceList = new ArrayList<ValueSource>();

    functions = (Map<String, CallableFunction>) fp.getReq().getContext().get(Loader.FUNCTIONS);

    Map<String, ValueSource> values = new HashMap<String, ValueSource>();

    int i = 0;
    while (fp.hasMoreArguments()) {
        rawargs[i++] = fp.parseArg();
    }

    functionName = rawargs[0];

    CallableFunction function = functions.get(functionName);

    //still need this?

    // FunctionExecutionContext cachedEC = (FunctionExecutionContext)fp.getReq().getContext().get(fp.getString() );
    /* if (cachedEC != null) {
       logger.error("reusing executor from cache!");
       return cachedEC.getFunctionExecutor();
    } */

    for (int k = 1; k < i; k++) {
        String parts[] = rawargs[k].split("=");
        String name = parts[0];
        String value = parts[1];

        args.put(parts[0], parts[1]);

        if (value.startsWith("\"") && value.endsWith("\"")) {
            //probably quite ineffcient..
            String v = value.replaceAll("^\"", "").replaceAll("\"$", "");
            LiteralValueSource l = new LiteralValueSource(v);
            values.put(name, l);
            valueSourceList.add(l);
        } else if (NumberUtils.isNumber(value)) {
            ConstValueSource cvs = new ConstValueSource(Float.parseFloat(value));
            values.put(name, cvs);
            valueSourceList.add(cvs);
        } else {
            SchemaField f = fp.getReq().getSchema().getField(value);
            ValueSource vs = f.getType().getValueSource(f, fp);
            values.put(name, vs);
            valueSourceList.add(vs);
        }

    }

    FunctionExecutor executor = new FunctionExecutor(values, valueSourceList, fp, this);

    executor.setFunction(functions.get(functionName));

    // still need this????
    FunctionExecutionContext ec = new FunctionExecutionContext(fp.getString(), values, function, executor);
    fp.getReq().getContext().put(fp.getString(), ec);

    return executor;

}

From source file:edu.snu.leader.hidden.builder.ConflictDistributionIndividualBuilder.java

/**
 * Initializes the builder//  ww w. jav  a2 s .c o m
 *
 * @param simState The simulation's state
 * @see edu.snu.leader.hidden.builder.AbstractIndividualBuilder#initialize(edu.snu.leader.hidden.SimulationState)
 */
@Override
public void initialize(SimulationState simState) {
    _LOG.trace("Entering initialize( simState )");

    // Call the superclass implementation
    super.initialize(simState);

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

    // Get the mean conflict value
    String conflictMeanStr = props.getProperty(_CONFLICT_MEAN_KEY);
    Validate.notEmpty(conflictMeanStr, "Conflict mean (key=" + _CONFLICT_MEAN_KEY + ") may not be empty");
    _conflictMean = Float.parseFloat(conflictMeanStr);
    _LOG.info("Using _conflictMean=[" + _conflictMean + "]");

    // Get the conflict value standard deviation
    String conflictStdDevStr = props.getProperty(_CONFLICT_STD_DEV_KEY);
    Validate.notEmpty(conflictStdDevStr,
            "Conflict std dev (key=" + _CONFLICT_STD_DEV_KEY + ") may not be empty");
    _conflictStdDev = Float.parseFloat(conflictStdDevStr);
    _LOG.info("Using _conflictStdDev=[" + _conflictStdDev + "]");

    // Get the min conflict
    String minConflictStr = props.getProperty(_MIN_CONFLICT_KEY);
    Validate.notEmpty(minConflictStr,
            "Minimum conflict value (key=" + _MIN_CONFLICT_KEY + ") may not be empty");
    _minConflict = Float.parseFloat(minConflictStr);
    _LOG.info("Using _minConflict=[" + _minConflict + "]");

    // Get the max conflict
    String maxConflictStr = props.getProperty(_MAX_CONFLICT_KEY);
    Validate.notEmpty(maxConflictStr,
            "Maximum conflict value (key=" + _MAX_CONFLICT_KEY + ") may not be empty");
    _maxConflict = Float.parseFloat(maxConflictStr);
    _LOG.info("Using _maxConflict=[" + _maxConflict + "]");

    // Get the random number distribution
    String rnDistStr = props.getProperty(_RNG_DIST_KEY);
    Validate.notEmpty(rnDistStr, "Random number distribution (key=" + _RNG_DIST_KEY + ") may not be empty");
    _rnDist = RNDistribution.valueOf(rnDistStr.toUpperCase());
    _LOG.info("Using _rnDist=[" + _rnDist + "]");

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