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]); } } }
/** * 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))); }
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 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"; }
// --------------------------------------------------------------------------- // 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()); }
/* 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); }
/** * 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)); }
/** 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()
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"; } }
/** * 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); }
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(); } } }
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(); } }
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)); }
// 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) { } }
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 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; }
// 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
/** * This function re-computes the total number of hours for the selected period. It is ran every * time the user edits a text field specifying the number of hours for a particular top-level * project. Percentage labels are also updated. */ private void recomputeTotal() { double total = 0; for (Row row : rows.values()) { try { row.hours = Double.parseDouble(row.hoursTF.getText()); total += row.hours; row.hoursTF.setForeground(normalColour); } catch (NumberFormatException e) { row.hoursTF.setForeground(errorColour); totalLabel.setText("ERROR"); totalLabel.setForeground(errorColour); return; } } totalLabel.setText(decimalFormat.format(total)); totalLabel.setForeground(normalColour); for (Row row : rows.values()) { String percentS = decimalFormat.format(total == 0 ? 0 : 100 * row.hours / total); row.percentL.setText("(" + percentS + "%)"); } pack(); }
private String generateOverviewText() throws InsufficientDataException { StringBuilder sb = new StringBuilder(); final String team = config.getTeam(); double total = checkTotal(); final String nl = System.getProperty("line.separator"); for (Entry<String, Row> entry : rows.entrySet()) { double hours = Double.parseDouble(entry.getValue().hoursTF.getText()); double fraction = hours / total; if (fraction < 0.004) continue; String line = team + ", " + decimalFormat.format(fraction) + ", " + entry.getKey(); sb.append(line + nl); } return sb.toString(); }
public String toString() { StringBuffer buf = new StringBuffer(); // buf.append( "\n" + this.statspec.getId() + "\n" ); if (this.min != null) buf.append(" min=" + format.format(this.min.doubleValue())); if (this.max != null) buf.append(" max=" + format.format(this.max.doubleValue())); if (this.maxminusmin != null) buf.append(" max-min=" + format.format(this.maxminusmin.doubleValue())); if (this.mean != null) buf.append(" mean=" + format.format(this.mean.doubleValue())); if (this.stddev != null) buf.append(" stddev=" + format.format(this.stddev.doubleValue())); if (!PerfReporter.brief) { // buf.append( " start=" + this.trimspec.getStartStr() ); // buf.append( " end=" + this.trimspec.getEndStr() ); buf.append("\n "); // buf.append( " isLargerBetter=" + this.isLargerBetter ); buf.append(" samples=" + this.samples); buf.append(" archives=" + this.archives); // buf.append( " version=" + this.productVersion ); } return buf.toString(); }
/** Converts a byte array into a String. */ protected static String byteArrayToString(byte[] array, boolean quote) { StringBuffer sb = new StringBuffer(); if (quote) sb.append('"'); for (int i = 0; i < array.length; i++) { int b = array[i] & 0xFF; if (b < 0x20 || b >= 0x7f) { sb.append('\\'); sb.append(byteFormat.format(b)); } else if (b == '"' || b == ';' || b == '\\') { sb.append('\\'); sb.append((char) b); } else sb.append((char) b); } if (quote) sb.append('"'); return sb.toString(); }
// 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
/** * 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"); }
public void printWeightUpdate() { String fileName = "WeightFile.txt"; try { FileWriter fileWriter = new FileWriter(fileName); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); System.out.println( "printWeightUpdate, put this i trainedWeights() and set isTrained to true"); // weights for the hidden layer for (Neuron n : hiddenLayer) { ArrayList<Connection> connections = n.getAllInConnections(); for (Connection con : connections) { String w = df.format(con.getWeight()); System.out.println( "weightUpdate.put(weightKey(" + n.id + ", " + con.id + "), " + w + ");"); bufferedWriter.write(ef.format(n.id)); bufferedWriter.write(" "); bufferedWriter.write(ef.format(con.id)); bufferedWriter.write(" "); bufferedWriter.write(w); bufferedWriter.newLine(); } } // weights for the output layer for (Neuron n : outputLayer) { ArrayList<Connection> connections = n.getAllInConnections(); for (Connection con : connections) { String w = df.format(con.getWeight()); System.out.println( "weightUpdate.put(weightKey(" + n.id + ", " + con.id + "), " + w + ");"); bufferedWriter.write(ef.format(n.id)); bufferedWriter.write(" "); bufferedWriter.write(ef.format(con.id)); bufferedWriter.write(" "); bufferedWriter.write(w); bufferedWriter.newLine(); } } System.out.println(); bufferedWriter.close(); } catch (IOException ex) { System.out.println("Error writing to file " + fileName); } }
public void printQs() { // Print Q-Values System.out.println("Q Values:"); System.out.println(rep("-", sizeX * 6 + 1)); for (int i = 0; i < sizeY; i++) { for (int j = 0; j < sizeX; j++) { if (isGoal(j, i) != null) { System.out.print("| G "); } else if (isAgentHome(j, i) != null) { System.out.print("| A "); } else { String t = " " + df.format(Q[j][i].maxReward()); t = t.substring(t.length() - 5); System.out.print("|" + t); } } System.out.println("|"); System.out.println(rep("-", sizeX * 6 + 1)); } }
public static void main(String[] args) { Scanner cin = new Scanner(System.in); while (true) { int num = cin.nextInt(); if (num == 0) break; int[] list = new int[num]; int max = 0; int min = 1000; int result = 0; int tmp = 0; for (int i = 0; i < num; i++) { tmp = cin.nextInt(); if (tmp > max) max = tmp; if (tmp < min) min = tmp; result += tmp; } result = (result - max - min) / (num - 2); DecimalFormat df = new DecimalFormat(""); System.out.println(df.format(result)); } }
/** main method - entry point for the entire program */ public static void main(String[] args) throws IOException // just let IOExceptions terminate the program { // initialize loan variables from constants final double principal = PRINCIPAL; final double rate = RATE / 100; // convert rate into decimal form final double numPayments = TERM * MONTHS_PER_YEAR; // create output and input objects final PrintStream out = System.out; final BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // display the header for this assignment out.println("Name : David C. Gibbons "); out.println("Assignment : Workshop 3 "); out.println("-------------------------------------"); // determine interest rate per month final double monthlyRate = (rate / MONTHS_PER_YEAR); // calculate monthly payment final double monthlyPayment = principal * (monthlyRate / (1 - Math.pow(1 + monthlyRate, -numPayments))); // fetch needed decimal formatters needed for output final DecimalFormat numberFmt = new DecimalFormat("#0"); final DecimalFormat currencyFmt = new DecimalFormat("$0.00"); final DecimalFormat percentFmt = new DecimalFormat("0.00 %"); // display overall loan information out.println("Principal : " + currencyFmt.format(principal)); out.println("Interest Rate : " + percentFmt.format(rate)); out.println("# of payments : " + numberFmt.format(numPayments)); out.println("Monthly payment : " + currencyFmt.format(monthlyPayment)); // wait for the user to continue and then display the // details of all the payments out.println(); out.println("Hit Enter to list Payment Detail"); in.readLine(); // calculate the payment detail in yearly blocks double currentPrincipal = principal; for (int month = 0; month < numPayments; month++) { // display header to match the benchmark at the start of the year if (month == 0 || (month % MONTHS_PER_YEAR) == 0) { // display a pause prompt if this isn't the first year if (month > 0) { out.println(); out.println(" Hit Enter to continue"); in.readLine(); } out.println(); out.println("\tInterest Principal Principal"); out.println("Months\tPayment Payment Balance"); out.println(); } // calculate this month's interest payment and then the // principal payment and remaining principal balance double interestPayment = rate / MONTHS_PER_YEAR * currentPrincipal; double principalPayment = monthlyPayment - interestPayment; // always get the absolute value of the current principal as // sometimes the final value of 0 can be -0.0 currentPrincipal = Math.abs(currentPrincipal - principalPayment); // format the fields and display to match benchmark out.print(numberFmt.format(month + 1) + " \t"); out.print(currencyFmt.format(interestPayment) + "\t "); out.print(currencyFmt.format(principalPayment) + "\t"); out.println(currencyFmt.format(currentPrincipal)); } }
/** convenience method for setting a double field */ public static void setFieldValue(JTextField field, double value) { DecimalFormat formatter = new DecimalFormat("0.0##E0"); field.setText(formatter.format(value)); }