Beispiel #1
0
  /**
   * Creates a byte array representation from the specified double value; inspired by Xavier Franc's
   * Qizx/open processor.
   *
   * @param dbl double value to be converted
   * @return byte array
   */
  public static byte[] token(final double dbl) {
    final byte[] b = tok(dbl);
    if (b != null) return b;

    final double a = Math.abs(dbl);
    return chopNumber(token(a >= 1e-6 && a < 1e6 ? DD.format(dbl) : SD.format(dbl)));
  }
Beispiel #2
0
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_report);
   Bundle bundle = getIntent().getExtras();
   double height = Double.parseDouble(bundle.getString("height")) / 100;
   double weight = Double.parseDouble(bundle.getString("weight"));
   double bmi = weight / (height * height);
   DecimalFormat nf = new DecimalFormat("0.00");
   TextView result = (TextView) findViewById(R.id.report_result);
   result.setText(getString(R.string.bmi_result) + " " + nf.format(bmi));
   // Give health advice
   ImageView image = (ImageView) findViewById(R.id.report_image);
   TextView advice = (TextView) findViewById(R.id.report_advice);
   if (bmi > 25) {
     image.setImageResource(R.drawable.bot_fat);
     advice.setText(R.string.advice_heavy);
   } else if (bmi < 20) {
     image.setImageResource(R.drawable.bot_thin);
     advice.setText(R.string.advice_light);
   } else {
     image.setImageResource(R.drawable.bot_fit);
     advice.setText(R.string.advice_average);
   }
 }
  /**
   * actionPerformed() handles clicks on the button. It takes the data from the input JTextFields,
   * and sends them to the GradeCalculater class to calculate a running average and computes the
   * letter grade, which are displayed in TextFields.
   *
   * @param e -- the ActionEvent the generated this system call
   */
  public void actionPerformed(ActionEvent e) {

    double count, grade = 0, ave;
    DecimalFormat df = new DecimalFormat("0.00");

    String inputString = inputField.getText();

    // HINT: use try/catch blocks to catch bad input to parseDouble()
    // Type mismatch
    // check for range too
    boolean error = true;

    try {
      grade = Double.parseDouble(inputString);
      error = false;
    } catch (Exception e1) {
      System.out.println("input a number");
    }

    // HINT: reject a bad grade in some way (the modified addGrade will return false
    // there is a problem with the grade

    // HINT: output grade count along with average and letter grade
    if (error == false) {
      inputField.setText("");
      calculator.addGrade(grade);
      ave = calculator.calcAvg();
      count = calculator.getCount();
      String average = "" + df.format(ave);
      String letterGrade = calculator.calcLetterGrade();
      resultField.setText(average + " " + letterGrade + " " + count);
    }
  } // actionPeformed()
Beispiel #4
0
 public static void main(String[] args) {
   DecimalFormat twoDigits = new DecimalFormat("#0.00");
   SalesApp mySalesApp = new SalesApp();
   int[] myArray = {4, 6, 7, 8};
   mySalesApp.setSales(myArray);
   System.out.println("Average Sale: " + twoDigits.format(mySalesApp.getAverage()));
   mySalesApp.calculateMinMax();
   int[] theSales = mySalesApp.getSales();
   System.out.println(
       "Salesperson "
           + (mySalesApp.getMin() + 1)
           + " had the lowest sale with $"
           + twoDigits.format(theSales[mySalesApp.getMin()]));
   System.out.println(
       "Salesperson "
           + (mySalesApp.getMax() + 1)
           + " had the lowest sale with $"
           + twoDigits.format(theSales[mySalesApp.getMax()]));
   mySalesApp.setSalesBar(6);
   int[] performance = mySalesApp.determineTopSalesPeople();
   for (int x = 0; x < performance.length; x++) {
     if (performance[x] == 1) {
       System.out.println(
           "Salesperson " + (x + 1) + " was over the goal and sold $" + theSales[x]);
     }
   }
 }
Beispiel #5
0
  static {
    // TODO: DecimalFormat uses ROUND_HALF_EVEN, not ROUND_HALF_UP
    // Float: precision of 7 (6 digits after .)
    floatFormatter = new DecimalFormat();
    floatFormatter.applyPattern("0.######E0");

    // Double: precision of 16 (15 digits after .)
    doubleFormatter = new DecimalFormat();
    doubleFormatter.applyPattern("0.###############E0");

    bigIntTenPow = new BigInteger[20];
    bigIntMinUnscaled = new BigInteger[20];
    bigIntMaxUnscaled = new BigInteger[20];

    for (int i = 0; i < bigIntTenPow.length; i++) {
      bigIntTenPow[i] = bigIntTen.pow(i);
      if (i < 19) {
        bigIntMaxUnscaled[i] = bigIntTenPow[i].subtract(BigInteger.ONE);
        bigIntMinUnscaled[i] = bigIntMaxUnscaled[i].negate();
      } else {
        bigIntMaxUnscaled[i] = BigInteger.valueOf(Long.MAX_VALUE);
        bigIntMinUnscaled[i] = BigInteger.valueOf(Long.MIN_VALUE);
      }
    }
  }
Beispiel #6
0
 public static String getDistanceText(long distance) {
   DecimalFormat df = new DecimalFormat("#0.0");
   if (distance >= (OSMParam.FEET_PER_MILE / 10)) {
     return df.format((double) distance / OSMParam.FEET_PER_MILE) + " miles";
   } else {
     return distance + " feets";
   }
 }
 public static void main(String[] args) {
   Scanner scanner = new Scanner(System.in);
   CreateShape cs = new CreateShape();
   cs.side1 = scanner.nextDouble();
   cs.side2 = scanner.nextDouble();
   DecimalFormat df = new DecimalFormat("###.####");
   System.out.println(df.format(cs.getArea()));
   System.out.print(df.format(cs.getPerimeter()));
 }
  public static void matrixToPanel(JTextField[] jtfMatrix, Matrix matrix) {
    int i, j;
    DecimalFormat df = new DecimalFormat(String.valueOf(matrix.getAccuracy()).replace('1', '0'));

    for (i = 0; i < matrix.getLine(); i++)
      for (j = 0; j < matrix.getRow(); j++) {
        jtfMatrix[i * matrix.getRow() + j].setText(
            String.valueOf(df.format(matrix.getElement(i, j))));
      }
  }
 public static String memoryToString() {
   DecimalFormat fmt = new DecimalFormat("0.0");
   return "Memory: "
       + fmt.format(RUNTIME.maxMemory() / 1048576D)
       + "MByte maximum, "
       + fmt.format(RUNTIME.totalMemory() / 1048576D)
       + "MByte total, "
       + fmt.format(RUNTIME.totalMemory() / 1048576D)
       + "MByte free";
 }
Beispiel #10
0
 // ---------------------------------------------------------------------------
 //  Returns pertinent information about the rectangle.
 // ---------------------------------------------------------------------------
 public String toString() {
   return "Rectangle: width is "
       + form.format(width)
       + ", length is "
       + form.format(length)
       + "\nperimeter is "
       + form.format(computePerimeter())
       + ", area is "
       + form.format(computeArea());
 }
Beispiel #11
0
  // calculate and display amounts
  private void calculateJButtonActionPerformed(ActionEvent event) {
    resultJTextArea.setText("Rate (%)\tAmount after 10 years");
    DecimalFormat dollars = new DecimalFormat("$0.00");

    int principal = Integer.parseInt(principalJTextField.getText());

    // for loop to calculate interest
    for (int rate = 5; rate <= 10; rate++) {
      double amount = (double) principal * Math.pow(1 + ((double) rate / 100), 10);
      resultJTextArea.append("\n" + rate + "\t" + dollars.format(amount));
    } // end for
  } // end method calculateJButtonActionPerformed
Beispiel #12
0
 /* paint() - get current time and draw (centered) in Component. */
 public void paint(Graphics g) {
   Calendar myCal = Calendar.getInstance();
   StringBuffer sb = new StringBuffer();
   sb.append(tf.format(myCal.get(Calendar.HOUR)));
   sb.append(':');
   sb.append(tflz.format(myCal.get(Calendar.MINUTE)));
   sb.append(':');
   sb.append(tflz.format(myCal.get(Calendar.SECOND)));
   String s = sb.toString();
   FontMetrics fm = getFontMetrics(getFont());
   int x = (getSize().width - fm.stringWidth(s)) / 2;
   // System.out.println("Size is " + getSize());
   g.drawString(s, x, 10);
 }
Beispiel #13
0
  /**
   * Creates a byte array representation from the specified float value.
   *
   * @param flt float value to be converted
   * @return byte array
   */
  public static byte[] token(final float flt) {
    final byte[] b = tok(flt);
    if (b != null) return b;

    // not that brilliant here.. no chance for elegant code either
    // due to the nifty differences between Java and XQuery
    for (int i = 0; i < FLT.length; ++i) if (flt == FLT[i]) return FLTSTR[i];
    final float a = Math.abs(flt);
    final boolean small = a >= 1e-6f && a < 1e6f;
    String s1 = small ? DF.format(flt) : SF.format(flt);
    final String s2 = Float.toString(flt);
    if (s2.length() < s1.length() && (!s2.contains("E") || !small)) s1 = s2;
    return chopNumber(token(s1));
  }
Beispiel #14
0
 /**
  * @bug 4135752 This would be better tested by the LocaleDataTest. Will move it when I get the
  *     LocaleDataTest working again.
  */
 public void TestThaiCurrencyFormat() {
   DecimalFormat thaiCurrency =
       (DecimalFormat) NumberFormat.getCurrencyInstance(new Locale("th", "TH"));
   if (!thaiCurrency.getPositivePrefix().equals("\u0e3f"))
     errln(
         "Thai currency prefix wrong: expected \"\u0e3f\", got \""
             + thaiCurrency.getPositivePrefix()
             + "\"");
   if (!thaiCurrency.getPositiveSuffix().equals(""))
     errln(
         "Thai currency suffix wrong: expected \"\", got \""
             + thaiCurrency.getPositiveSuffix()
             + "\"");
 }
Beispiel #15
0
  static {
    nf = DecimalFormat.getInstance();
    nf.setMaximumFractionDigits(6);
    nf.setMinimumFractionDigits(6);

    sci = new DecimalFormat("0.0000E0");
  }
Beispiel #16
0
 /**
  * Adds an editable text field containing the hours spent on a project.
  *
  * @param gbl The layout to add the text field to.
  * @param gbc The layout constraints to use.
  * @param row The row to link against.
  * @param hours The number of hours spent on the project.
  * @see {@link #addRow(GridBagLayout, GridBagConstraints, String, double)}
  */
 private void addMiddleField(GridBagLayout gbl, GridBagConstraints gbc, Row row, double hours) {
   row.hoursTF.setText(decimalFormat.format(hours));
   gbc.gridx = 1;
   gbc.weightx = 1;
   gbl.setConstraints(row.hoursTF, gbc);
   gbc.weightx = 0;
   reviewPanel.add(row.hoursTF);
 }
Beispiel #17
0
  public static void test1() {
    Sequence[] seqs = Parser.test1();
    double[][] distances = (new GappedHammingDistance()).getDistanceMatrix(seqs);
    DecimalFormat f = new DecimalFormat("0000.000");

    System.out.println("   " + seqs.length);

    for (int i = 0; i < seqs.length; i++) {
      System.out.print(seqs[i].name);
      for (int k = 0; k < 10 - seqs[i].name.length(); k++) {
        System.out.print(" ");
      }
      System.out.print("  ");
      int cols = 1;
      for (int j = 0; j < seqs.length; j++) {
        if (i != j) {
          int di = i;
          int dj = j;
          // force symmetric matrix - arg - what the???
          // testing!!!
          if (j > i) {
            di = j;
            dj = i;
          }
          double d = distances[di][dj];
          // testing
          if (d > 2000) {
            System.err.println("ARGH");
          }
          System.out.print(f.format(d));
        } else {
          System.out.print(f.format(0));
        }
        System.out.print("  ");
        cols++;
        if (cols >= 7) {
          System.out.println();
          System.out.print("  ");
          cols = 0;
        }
      }
      if (cols != 7) {
        System.out.println();
      }
    }
  }
  // calculate and display amounts
  private void calculateJButtonActionPerformed(ActionEvent event) {
    // declare variables to store user input
    double principal = Double.parseDouble(principalJTextField.getText());
    double rate = Double.parseDouble(interestRateJTextField.getText());

    Integer integerObject = (Integer) yearsJSpinner.getValue();
    Integer year = integerObject.intValue();

    yearlyBalanceJTextArea.setText("Year\tAmount on Deposit");
    DecimalFormat dollars = new DecimalFormat("$0.00");

    // calculate the total value for each year
    for (int count = 1; count <= year; count++) {
      double amount = principal * Math.pow((1 + rate / 100), count);
      yearlyBalanceJTextArea.append("\n" + count + "\t" + dollars.format(amount));
    } // end for
  } // end method calculateJButtonActionPerformed
Beispiel #19
0
  /**
   * This is a sample of creating a new Population with 'size_population' organisms , and simulation
   * of XOR example This sample can be started in two modality : -cold : each time the population is
   * re-created from 0; -warm : each time the population re-read last population created and restart
   * from last epoch. (the population backup file is : 'c:\\jneat\\dati\\population.primitive'
   */
  public static void Experiment3(int size_population, int mode, int gens) {
    Population pop = null;
    String fname_prefix = "c:\\jneat\\dati\\population.primitive";
    String fnamebuf;
    int gen;
    int id;
    int expcount = 0;
    String mask6 = "000000";
    DecimalFormat fmt6 = new DecimalFormat(mask6);

    System.out.println("------ Start experiment 3 -------");

    for (expcount = 0; expcount < Neat.p_num_runs; expcount++) {
      System.out.println(" Spawned population off genome");

      double prb_link = 0.50;
      boolean recurrent = true;

      // default cold is : 3 sensor (1 for bias) , 1 out , 5 nodes max, no recurrent
      if (mode == NeatConstant.COLD)
        pop = new Population(size_population, 3, 1, 5, recurrent, prb_link); // cold start-up
      //		   pop = new Population(size_population, 3, 1, 5, recurrent, prb_link);		// cold start-up
      else pop = new Population(fname_prefix + ".last"); // warm start-up

      pop.verify();
      System.out.print("\n---------------- Generation starting with----------");
      System.out.print("\n  Population : innov num   = " + pop.getCur_innov_num());
      System.out.print("\n             : cur_node_id = " + pop.getCur_node_id());
      System.out.print("\n---------------------------------------------------");

      System.out.print("\n");
      for (gen = 1; gen <= gens; gen++) {
        System.out.print("\n---------------- Generation ----------------------" + gen);
        fnamebuf = "g_" + fmt6.format(gen);
        boolean esito = xor_epoch(pop, gen, fnamebuf);
        System.out.print("\n  Population : innov num   = " + pop.getCur_innov_num());
        System.out.print("\n             : cur_node_id = " + pop.getCur_node_id());
        System.out.print("\n   result    : " + esito);
      }
    }

    // backup of population for warm startup
    pop.print_to_filename(fname_prefix + ".last");

    System.out.println("\n\n End of experiment");
  }
Beispiel #20
0
  private Number parseNumber(int max, String string, ParsePosition position) {
    int length = string.length();
    int index = position.getIndex();
    if (max > 0 && max < length - index) {
      length = index + max;
    }
    while (index < length && (string.charAt(index) == ' ' || string.charAt(index) == '\t')) {
      ++index;
    }
    if (max == 0) {
      position.setIndex(index);
      Number n = numberFormat.parse(string, position);
      // In RTL locales, NumberFormat might have parsed "2012-" in an ISO date as the
      // negative number -2012.
      // Ideally, we wouldn't have this broken API that exposes a NumberFormat and expects
      // us to use it. The next best thing would be a way to ask the NumberFormat to parse
      // positive numbers only, but icu4c supports negative (BCE) years. The best we can do
      // is try to recognize when icu4c has done this, and undo it.
      if (n != null && n.longValue() < 0) {
        if (numberFormat instanceof DecimalFormat) {
          DecimalFormat df = (DecimalFormat) numberFormat;
          char lastChar = string.charAt(position.getIndex() - 1);
          char minusSign = df.getDecimalFormatSymbols().getMinusSign();
          if (lastChar == minusSign) {
            n = Long.valueOf(-n.longValue()); // Make the value positive.
            position.setIndex(position.getIndex() - 1); // Spit out the negative sign.
          }
        }
      }
      return n;
    }

    int result = 0;
    int digit;
    while (index < length && (digit = Character.digit(string.charAt(index), 10)) != -1) {
      result = result * 10 + digit;
      ++index;
    }
    if (index == position.getIndex()) {
      position.setErrorIndex(index);
      return null;
    }
    position.setIndex(index);
    return Integer.valueOf(result);
  }
  public static void main(String[] args) {
    // input arg is the radius of the circle
    String radiusStr = args[0];
    final double PI = 3.14159;
    DecimalFormat df = new DecimalFormat("0.000");

    double radius, area, circumference;

    radius = Double.parseDouble(radiusStr);

    // compute area and circumference
    area = PI * radius * radius;
    circumference = 2.0 * PI * radius;

    System.out.println("Given Radius:  " + radius);
    System.out.println("Area:          " + df.format(area));
    System.out.println("circumference: " + df.format(circumference));
  }
  public void write(long time, Instrument instrument1, Instrument instrument2) {
    double bid1 = instrument1.getBid();
    double ask1 = instrument1.getAsk();
    double bid2 = instrument2.getBid();
    double ask2 = instrument2.getAsk();

    if (bid1 > 0 && ask1 > 0 && bid2 > 0 && ask2 > 0) {
      StringBuilder sb = new StringBuilder();
      sb.append(dateFormat.format(new Date(time))).append(",");
      sb.append(decimalFormat.format(bid1)).append(",");
      sb.append(decimalFormat.format(ask1)).append(",");
      sb.append(decimalFormat.format(bid2)).append(",");
      sb.append(decimalFormat.format(ask2));

      writer.println(sb);
      writer.flush();
    }
  }
Beispiel #23
0
  //    int frame = 0;
  public void paint(Graphics g) {
    // System.out.println("frame: " + (frame++));
    lStatus.setText(
        "t = "
            + df.format(md.dt * md.step)
            + ", "
            + "N = "
            + md.N
            + ", "
            + "E/N = "
            + df.format(md.E / md.N)
            + ", "
            + "U/N = "
            + df.format(md.U / md.N)
            + ", "
            + "K/N = "
            + df.format(md.K / md.N)
            + ", "
            + "p = "
            + df.format(md.p)
            + ";");
    tAvK.setText(df.format(md.avK.getAve() / md.N) + "  ");
    tAvU.setText(df.format(md.avU.getAve() / md.N) + "  ");
    tTemp.setText(df.format((2 * md.K) / (3 * (md.N - 1))) + "  ");
    tAvp.setText(df.format(md.avp.getAve()) + "  ");
    canvas.refresh(md.getXWrap(), md.N, true, false);
    cpnl.repaint();
    spnl.repaint();

    try {

      PrintWriter wavefunc =
          new PrintWriter(new FileOutputStream(new File("energyData.txt"), true));
      wavefunc.print(md.E / md.N + " " + md.K / md.N + " " + md.U / md.N);
      wavefunc.println();
      wavefunc.close();
    } catch (IOException ex) {
    }

    try {

      PrintWriter tempwriter =
          new PrintWriter(new FileOutputStream(new File("tempData.txt"), true));
      tempwriter.print(df.format((2 * md.K) / (3 * (md.N - 1))));
      tempwriter.println();
      tempwriter.close();
    } catch (IOException ex) {
    }
  }
    // Recompute the locale-based formatter.
    void setLocale(Locale loc) {
      if (type == null) ;
      else if (type.equals("number")) {
        formatClass = java.lang.Number.class;

        if (style == null) format = NumberFormat.getInstance(loc);
        else if (style.equals("currency")) format = NumberFormat.getCurrencyInstance(loc);
        else if (style.equals("percent")) format = NumberFormat.getPercentInstance(loc);
        else if (style.equals("integer")) {
          NumberFormat nf = NumberFormat.getNumberInstance(loc);
          nf.setMaximumFractionDigits(0);
          nf.setGroupingUsed(false);
          format = nf;
        } else {
          format = NumberFormat.getNumberInstance(loc);
          DecimalFormat df = (DecimalFormat) format;
          df.applyPattern(style);
        }
      } else if (type.equals("time") || type.equals("date")) {
        formatClass = java.util.Date.class;

        int val = DateFormat.DEFAULT;
        boolean styleIsPattern = false;
        if (style == null) ;
        else if (style.equals("short")) val = DateFormat.SHORT;
        else if (style.equals("medium")) val = DateFormat.MEDIUM;
        else if (style.equals("long")) val = DateFormat.LONG;
        else if (style.equals("full")) val = DateFormat.FULL;
        else styleIsPattern = true;

        if (type.equals("time")) format = DateFormat.getTimeInstance(val, loc);
        else format = DateFormat.getDateInstance(val, loc);

        if (styleIsPattern) {
          SimpleDateFormat sdf = (SimpleDateFormat) format;
          sdf.applyPattern(style);
        }
      } else if (type.equals("choice")) {
        formatClass = java.lang.Number.class;

        if (style == null) throw new IllegalArgumentException("style required for choice format");
        format = new ChoiceFormat(style);
      }
    }
Beispiel #25
0
 /**
  * Dem Konstruktor wird ein Formatstring uebergeben. Aus diesem Formatstring liesst das Textfeld
  * heraus wieviele Ziffern maximal eingegeben werden koennen, und wie gross die Anzeige sein soll.
  *
  * @param formatString DOCUMENT ME!
  */
 public DateField(final String formatString) {
   super(formatString.length());
   bringFocus2Next = false;
   maxLength = formatString.length();
   integerFormatter = new DecimalFormat(formatString);
   toolkit = Toolkit.getDefaultToolkit();
   // integerFormatter = NumberFormat.getNumberInstance();//Locale.US);
   integerFormatter.setParseIntegerOnly(true);
   addFocusListener(this);
 }
 public Object parseObject(String source) {
   try {
     if (StringUtils.isEmpty(source)) {
       return "";
     }
     return format.parseObject(source);
   } catch (ParseException e) {
     throw new AWSystemException("Error Parsing:<" + source + ">", e);
   }
 }
Beispiel #27
0
 /**
  * Mit dieser Methode kann der int-Wert des Feldes bestimmt werden.
  *
  * @return DOCUMENT ME!
  */
 public int getValue() {
   int retVal = 0;
   try {
     retVal = integerFormatter.parse(getText()).intValue();
   } catch (ParseException e) {
     // This should never happen because insertString allows
     // only properly formatted data to get in the field.
     toolkit.beep();
   }
   return retVal;
 }
 public ScientificRenderer(int sigfigs) {
   sigfigs = Math.min(sigfigs, 6);
   if (format instanceof DecimalFormat) {
     String pattern = "0.0"; // $NON-NLS-1$
     for (int i = 0; i < sigfigs - 1; i++) {
       pattern += "0"; // $NON-NLS-1$
     }
     pattern += "E0"; // $NON-NLS-1$
     ((DecimalFormat) format).applyPattern(pattern);
   }
 }
  public Object format(Object attributeValue) {
    if (attributeValue == null) return null;

    if (attributeValue instanceof String) {
      if (StringUtils.isEmpty((String) attributeValue)) {
        return null;
      }
      logger.info(" attributeValue is String <" + attributeValue + "> convert to new BigDecimal()");
      attributeValue = new BigDecimal(attributeValue.toString());
    }
    return format.format(attributeValue);
  }
  public static final String number2String(double value) {
    String str = null;
    if (isIntegerValue(value) == true) {
      int ivalue = (int) value;
      str = Integer.toString(ivalue);
    } else {
      // str = Double.toString(value);
      str = number2StringDecimalFormat.format(value);
    }

    return str;
  }