Example usage for java.lang Float Float

List of usage examples for java.lang Float Float

Introduction

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

Prototype

@Deprecated(since = "9")
public Float(String s) throws NumberFormatException 

Source Link

Document

Constructs a newly allocated Float object that represents the floating-point value of type float represented by the string.

Usage

From source file:Main.java

public static void main(String args[]) {
    JFrame frame = new JFrame();
    final JFormattedTextField textField1 = new JFormattedTextField(new Float(10.01));
    textField1.setFormatterFactory(new AbstractFormatterFactory() {
        @Override/*from   w  w  w  . j a v a 2s  .co  m*/
        public AbstractFormatter getFormatter(JFormattedTextField tf) {
            NumberFormat format = DecimalFormat.getInstance();
            format.setMinimumFractionDigits(2);
            format.setMaximumFractionDigits(2);
            format.setRoundingMode(RoundingMode.HALF_UP);
            InternationalFormatter formatter = new InternationalFormatter(format);
            formatter.setAllowsInvalid(false);
            formatter.setMinimum(0.0);
            formatter.setMaximum(1000.00);
            return formatter;
        }
    });
    NumberFormat numberFormat = NumberFormat.getNumberInstance();
    numberFormat.setMaximumFractionDigits(2);
    numberFormat.setMaximumFractionDigits(2);
    numberFormat.setRoundingMode(RoundingMode.HALF_UP);
    final JFormattedTextField textField2 = new JFormattedTextField(numberFormat);
    textField2.setValue(new Float(10.01));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(textField1, BorderLayout.NORTH);
    frame.add(textField2, BorderLayout.SOUTH);
    frame.setVisible(true);
    frame.pack();
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Boolean refBoolean = new Boolean(true);
    boolean bool = refBoolean.booleanValue();

    Byte refByte = new Byte((byte) 123);
    byte b = refByte.byteValue();

    Character refChar = new Character('x');
    char c = refChar.charValue();

    Short refShort = new Short((short) 123);
    short s = refShort.shortValue();

    Integer refInt = new Integer(123);
    int i = refInt.intValue();

    Long refLong = new Long(123L);
    long l = refLong.longValue();

    Float refFloat = new Float(12.3F);
    float f = refFloat.floatValue();

    Double refDouble = new Double(12.3D);
    double d = refDouble.doubleValue();
}

From source file:Main.java

public static void main(String args[]) {
    JFrame frame = new JFrame();
    final JFormattedTextField textField1 = new JFormattedTextField(new Float(10.01));
    textField1.setFormatterFactory(new AbstractFormatterFactory() {
        @Override/*from   w  w w. ja  v a  2s.c  o m*/
        public AbstractFormatter getFormatter(JFormattedTextField tf) {
            NumberFormat format = DecimalFormat.getInstance();
            format.setMinimumFractionDigits(2);
            format.setMaximumFractionDigits(2);
            format.setRoundingMode(RoundingMode.HALF_UP);
            InternationalFormatter formatter = new InternationalFormatter(format);
            formatter.setAllowsInvalid(false);
            formatter.setMinimum(0.0);
            formatter.setMaximum(1000.00);
            return formatter;
        }
    });
    Map attributes = (new Font("Serif", Font.BOLD, 16)).getAttributes();
    attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
    final JFormattedTextField textField2 = new JFormattedTextField(new Float(10.01));
    textField2.setFormatterFactory(new AbstractFormatterFactory() {

        @Override
        public AbstractFormatter getFormatter(JFormattedTextField tf) {
            NumberFormat format = DecimalFormat.getInstance();
            format.setMinimumFractionDigits(2);
            format.setMaximumFractionDigits(2);
            format.setRoundingMode(RoundingMode.HALF_UP);
            InternationalFormatter formatter = new InternationalFormatter(format);
            formatter.setAllowsInvalid(false);
            formatter.setMinimum(0.0);
            formatter.setMaximum(1000.00);
            return formatter;
        }
    });
    textField2.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void changedUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        @Override
        public void insertUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        @Override
        public void removeUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        private void printIt(DocumentEvent documentEvent) {
            DocumentEvent.EventType type = documentEvent.getType();
            double t1a1 = (((Number) textField2.getValue()).doubleValue());
            if (t1a1 > 100) {
                textField2.setFont(new Font(attributes));
                textField2.setForeground(Color.red);
            } else {
                textField2.setFont(new Font("Serif", Font.BOLD, 16));
                textField2.setForeground(Color.black);
            }
        }
    });
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(textField1, BorderLayout.NORTH);
    frame.add(textField2, BorderLayout.SOUTH);
    frame.setVisible(true);
    frame.pack();
}

From source file:Main.java

public static void main(String[] argv) {
    DefaultTableModel model = new DefaultTableModel() {
        public Class getColumnClass(int columnIndex) {
            Object o = getValueAt(0, columnIndex);
            if (o == null) {
                return Object.class;
            } else {
                return o.getClass();
            }/*  ww w . j a v  a 2s.com*/
        }
    };
    JTable table = new JTable(model);

    model.addColumn("Boolean", new Object[] { Boolean.TRUE });
    model.addColumn("Date", new Object[] { new Date() });
    model.addColumn("Double", new Object[] { new Double(Math.PI) });
    model.addColumn("Float", new Object[] { new Float(1.2) });
    model.addColumn("Icon", new Object[] { new ImageIcon("icon.gif") });
    model.addColumn("Number", new Object[] { new Integer(1) });
    model.addColumn("Object", new Object[] { "object" });

    JFrame f = new JFrame();
    f.setSize(300, 300);
    f.add(new JScrollPane(table));
    f.setVisible(true);
}

From source file:Main.java

public static void main(String[] argv) {
    DefaultTableModel model = new DefaultTableModel() {
        public Class getColumnClass(int columnIndex) {
            Object o = getValueAt(0, columnIndex);
            if (o == null) {
                return Object.class;
            } else {
                return o.getClass();
            }/* w w  w  .  j  av a 2s  . c  o m*/
        }
    };
    JTable table = new JTable(model);

    model.addColumn("Boolean", new Object[] { Boolean.TRUE });
    model.addColumn("Date", new Object[] { new Date() });
    model.addColumn("Double", new Object[] { new Double(Math.PI) });
    model.addColumn("Float", new Object[] { new Float(1.2) });
    model.addColumn("Icon", new Object[] { new ImageIcon("icon.gif") });
    model.addColumn("Number", new Object[] { new Integer(1) });
    model.addColumn("Object", new Object[] { "object" });

    Enumeration e = table.getColumnModel().getColumns();
    TableColumn col = (TableColumn) e.nextElement();

    col.setCellRenderer(table.getDefaultRenderer(Boolean.class));
    col.setCellEditor(table.getDefaultEditor(Boolean.class));

    JFrame f = new JFrame();
    f.setSize(300, 300);
    f.add(new JScrollPane(table));
    f.setVisible(true);
}

From source file:NumberDemo.java

public static void main(String args[]) {
    Float one = new Float(14.78f - 13.78f);
    Float oneAgain = Float.valueOf("1.0");
    Double doubleOne = new Double(1.0);

    int difference = one.compareTo(oneAgain);

    if (difference == 0) {
        System.out.println("one is equal to oneAgain.");
    } else if (difference < 0) {
        System.out.println("one is less than oneAgain.");
    } else if (difference > 0) {
        System.out.println("one is greater than oneAgain.");
    }//from  w ww  .j  a  va 2 s  .  c  o  m

    System.out.println("one is " + ((one.equals(doubleOne)) ? "equal" : "not equal") + " to doubleOne.");

}

From source file:gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCFormInstructionDAO.java

/**
 * Test application//from   w w  w .ja  va2 s.com
 */
public static void main(String[] args) {
    ServiceLocator locator = new SimpleServiceLocator();
    JDBCFormInstructionDAO test = new JDBCFormInstructionDAO(locator);

    // test createFormInstructionComponent method.
    // for each test, change long name(preferred name generated from long name)
    try {
        JDBCFormDAO formDao = new JDBCFormDAO(locator);
        String formId = "A019BB52-B911-3D6B-E034-080020C9C0E0";
        Form aForm = formDao.findFormByPrimaryKey(formId);

        Instruction newFormInstr = new InstructionTransferObject();
        newFormInstr.setVersion(new Float(2.31));
        newFormInstr.setIdseq("EBB3B308-4595-522D-E034-0003BA0B1A09");
        newFormInstr.setLongName("Testsh121-updated");
        newFormInstr.setPreferredDefinition("Test Form instr pref def");
        newFormInstr.setConteIdseq("99BA9DC8-2095-4E69-E034-080020C9C0E0");
        newFormInstr.setAslName("DRAFT NEW");
        newFormInstr.setCreatedBy("Hyun Kim");
        newFormInstr.setDisplayOrder(1);
        // int res = test.createInstruction(newFormInstr,formId,"FORM_INSTR","FORM_INSTRUCTION");
        //System.out.println("\n*****Create Form Instruction: " + res);

        //System.out.println("\n*****Query Form Instruction: " +test.getInstructions(formId));
        //System.out.println("\n*****Update Form Instruction: " +test.updateInstruction(newFormInstr));

        System.out.println("\n*****Deleted Form Instruction: "
                + test.deleteInstruction("EBB3B308-4595-522D-E034-0003BA0B1A09"));

    } catch (DMLException de) {
        de.printStackTrace();
    }

}

From source file:com.pymmasoftware.demo.loyalty.client.StandaloneLoyaltyClient.java

public static void main(String[] args) throws InterruptedException, ParseException {
    ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/application-context.xml");

    StandaloneLoyaltyClient loyaltyClient = context.getBean(StandaloneLoyaltyClient.class);
    Ticket ticket = new Ticket();
    ticket.setAmount(1000.0f);// w w w. j a  v a 2  s  .  co  m
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    ticket.setDateTicket(sdf.parse("01/01/2012"));
    ticket.setId("1");

    Card loyaltyCard = new Card();
    loyaltyCard.setCartType("Gold");
    loyaltyCard.setName("VISA");
    loyaltyCard.setName("4859569558");
    Customer customer = new Customer();
    customer.setCustomerID("12");
    customer.setBirthDate(sdf.parse("23/08/1968"));
    customer.setName("Heron");
    customer.setSurName("Nicolas");
    customer.setGender(Gender.Mr);
    loyaltyCard.setCustomer(customer);
    ticket.setLoyaltyCard(loyaltyCard);
    Provider provider = new Provider();
    provider.setName("Pymma Software");
    provider.setCountry("fr");
    Price price = new Price();
    price.setCurrency(Currency.Euro);
    price.setPrice(new Float("100.0"));
    Product product = new Product();
    product.setPrice(price);
    product.setProvider(provider);
    product.setId("100-100");
    product.setName("Pampers");
    ticket.AddLine(product, new Float("100.0"), 10);

    while (true) {
        ticket = loyaltyClient.fireAllRules(ticket);
        logger.info("Ticket processed : {}", ticket);
        sleep(30000);
    }

}

From source file:joshelser.as2015.query.Query.java

public static void main(String[] args) throws Exception {
    JCommander commander = new JCommander();
    final Opts options = new Opts();
    commander.addObject(options);//from w ww . jav  a  2  s  .c o m

    commander.setProgramName("Query");
    try {
        commander.parse(args);
    } catch (ParameterException ex) {
        commander.usage();
        System.err.println(ex.getMessage());
        System.exit(1);
    }

    ClientConfiguration conf = ClientConfiguration.loadDefault();
    if (null != options.clientConfFile) {
        conf = new ClientConfiguration(new PropertiesConfiguration(options.clientConfFile));
    }
    conf.withInstance(options.instanceName).withZkHosts(options.zookeepers);

    ZooKeeperInstance inst = new ZooKeeperInstance(conf);
    Connector conn = inst.getConnector(options.user, new PasswordToken(options.password));

    BatchScanner bs = conn.createBatchScanner(options.table, Authorizations.EMPTY, 16);
    try {
        bs.setRanges(Collections.singleton(new Range()));
        final Text categoryText = new Text("category");
        bs.fetchColumn(categoryText, new Text("name"));
        bs.fetchColumn(new Text("review"), new Text("score"));
        bs.fetchColumn(new Text("review"), new Text("userId"));

        bs.addScanIterator(new IteratorSetting(50, "wri", WholeRowIterator.class));
        final Text colf = new Text();
        Map<String, List<Integer>> scoresByUser = new HashMap<>();
        for (Entry<Key, Value> entry : bs) {
            SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
            Iterator<Entry<Key, Value>> iter = row.entrySet().iterator();
            if (!iter.hasNext()) {
                // row was empty
                continue;
            }
            Entry<Key, Value> categoryEntry = iter.next();
            categoryEntry.getKey().getColumnFamily(colf);
            if (!colf.equals(categoryText)) {
                throw new IllegalArgumentException("Unknown!");
            }
            if (!categoryEntry.getValue().toString().equals("books")) {
                // not a book review
                continue;
            }

            if (!iter.hasNext()) {
                continue;
            }
            Entry<Key, Value> reviewScore = iter.next();
            if (!iter.hasNext()) {
                continue;
            }
            Entry<Key, Value> reviewUserId = iter.next();

            String userId = reviewUserId.getValue().toString();
            if (userId.equals("unknown")) {
                // filter unknow user id
                continue;
            }

            List<Integer> scores = scoresByUser.get(userId);
            if (null == scores) {
                scores = new ArrayList<>();
                scoresByUser.put(userId, scores);
            }
            scores.add(Float.valueOf(reviewScore.getValue().toString()).intValue());
        }

        for (Entry<String, List<Integer>> entry : scoresByUser.entrySet()) {
            int sum = 0;
            for (Integer val : entry.getValue()) {
                sum += val;
            }

            System.out.println(entry.getKey() + " => " + new Float(sum) / entry.getValue().size());
        }
    } finally {
        bs.close();
    }
}

From source file:it.unipd.dei.ims.falcon.CmdLine.java

public static void main(String[] args) {

    // last argument is always index path
    Options options = new Options();
    // one of these actions has to be specified
    OptionGroup actionGroup = new OptionGroup();
    actionGroup.addOption(new Option("i", true, "perform indexing")); // if dir, all files, else only one file
    actionGroup.addOption(new Option("q", true, "perform a single query"));
    actionGroup.addOption(new Option("b", false, "perform a query batch (read from stdin)"));
    actionGroup.setRequired(true);//ww w.  j a v  a2s  . c  o  m
    options.addOptionGroup(actionGroup);

    // other options
    options.addOption(new Option("l", "segment-length", true, "length of a segment (# of chroma vectors)"));
    options.addOption(
            new Option("o", "segment-overlap", true, "overlap portion of a segment (# of chroma vectors)"));
    options.addOption(new Option("Q", "quantization-level", true, "quantization level for chroma vectors"));
    options.addOption(new Option("k", "min-kurtosis", true, "minimum kurtosis for indexing chroma vectors"));
    options.addOption(new Option("s", "sub-sampling", true, "sub-sampling of chroma features"));
    options.addOption(new Option("v", "verbose", false, "verbose output (including timing info)"));
    options.addOption(new Option("T", "transposition-estimator-strategy", true,
            "parametrization for the transposition estimator strategy"));
    options.addOption(new Option("t", "n-transp", true,
            "number of transposition; if not specified, no transposition is performed"));
    options.addOption(new Option("f", "force-transp", true, "force transposition by an amount of semitones"));
    options.addOption(new Option("p", "pruning", false,
            "enable query pruning; if -P is unspecified, use default strategy"));
    options.addOption(new Option("P", "pruning-custom", true, "custom query pruning strategy"));

    // parse
    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
        if (cmd.getArgs().length != 1)
            throw new ParseException("no index path was specified");
    } catch (ParseException ex) {
        System.err.println("ERROR - parsing command line:");
        System.err.println(ex.getMessage());
        formatter.printHelp("falcon -{i,q,b} [options] index_path", options);
        return;
    }

    // default values
    final float[] DEFAULT_TRANSPOSITION_ESTIMATOR_STRATEGY = new float[] { 0.65192807f, 0.0f, 0.0f, 0.0f,
            0.3532628f, 0.4997167f, 0.0f, 0.41703504f, 0.0f, 0.16297342f, 0.0f, 0.0f };
    final String DEFAULT_QUERY_PRUNING_STRATEGY = "ntf:0.340765*[0.001694,0.995720];ndf:0.344143*[0.007224,0.997113];"
            + "ncf:0.338766*[0.001601,0.995038];nmf:0.331577*[0.002352,0.997884];"; // TODO not the final one

    int hashes_per_segment = Integer.parseInt(cmd.getOptionValue("l", "150"));
    int overlap_per_segment = Integer.parseInt(cmd.getOptionValue("o", "50"));
    int nranks = Integer.parseInt(cmd.getOptionValue("Q", "3"));
    int subsampling = Integer.parseInt(cmd.getOptionValue("s", "1"));
    double minkurtosis = Float.parseFloat(cmd.getOptionValue("k", "-100."));
    boolean verbose = cmd.hasOption("v");
    int ntransp = Integer.parseInt(cmd.getOptionValue("t", "1"));
    TranspositionEstimator tpe = null;
    if (cmd.hasOption("t")) {
        if (cmd.hasOption("T")) {
            // TODO this if branch is yet to test
            Pattern p = Pattern.compile("\\d\\.\\d*");
            LinkedList<Double> tokens = new LinkedList<Double>();
            Matcher m = p.matcher(cmd.getOptionValue("T"));
            while (m.find())
                tokens.addLast(new Double(cmd.getOptionValue("T").substring(m.start(), m.end())));
            float[] strategy = new float[tokens.size()];
            if (strategy.length != 12) {
                System.err.println("invalid transposition estimator strategy");
                System.exit(1);
            }
            for (int i = 0; i < strategy.length; i++)
                strategy[i] = new Float(tokens.pollFirst());
        } else {
            tpe = new TranspositionEstimator(DEFAULT_TRANSPOSITION_ESTIMATOR_STRATEGY);
        }
    } else if (cmd.hasOption("f")) {
        int[] transps = parseIntArray(cmd.getOptionValue("f"));
        tpe = new ForcedTranspositionEstimator(transps);
        ntransp = transps.length;
    }
    QueryPruningStrategy qpe = null;
    if (cmd.hasOption("p")) {
        if (cmd.hasOption("P")) {
            qpe = new StaticQueryPruningStrategy(cmd.getOptionValue("P"));
        } else {
            qpe = new StaticQueryPruningStrategy(DEFAULT_QUERY_PRUNING_STRATEGY);
        }
    }

    // action
    if (cmd.hasOption("i")) {
        try {
            Indexing.index(new File(cmd.getOptionValue("i")), new File(cmd.getArgs()[0]), hashes_per_segment,
                    overlap_per_segment, subsampling, nranks, minkurtosis, tpe, verbose);
        } catch (IndexingException ex) {
            Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    if (cmd.hasOption("q")) {
        String queryfilepath = cmd.getOptionValue("q");
        doQuery(cmd, queryfilepath, hashes_per_segment, overlap_per_segment, nranks, subsampling, tpe, ntransp,
                minkurtosis, qpe, verbose);
    }
    if (cmd.hasOption("b")) {
        try {
            long starttime = System.currentTimeMillis();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            while ((line = in.readLine()) != null && !line.trim().isEmpty())
                doQuery(cmd, line, hashes_per_segment, overlap_per_segment, nranks, subsampling, tpe, ntransp,
                        minkurtosis, qpe, verbose);
            in.close();
            long endtime = System.currentTimeMillis();
            System.out.println(String.format("total time: %ds", (endtime - starttime) / 1000));
        } catch (IOException ex) {
            Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}