/** * 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 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 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"; }
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)))); } }
/** * 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)); }
/* 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); }
static { nf = DecimalFormat.getInstance(); nf.setMaximumFractionDigits(6); nf.setMinimumFractionDigits(6); sci = new DecimalFormat("0.0000E0"); }
/** * 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); }
/** * 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 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(); } }
/** * 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(); }
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)); } }
/** * Конвертация строки типа: 5 Minutes * * @param str * @return */ private static int parseDuration(String str) throws ParseException { int idx = str.indexOf(' '); float num = DF.parse(str.substring(0, idx)).floatValue(); switch (str.substring(idx + 1)) { case "Seconds": return Math.round(num); case "Minutes": return Math.round(num * 60); default: throw new ParseException("Неизвестный формат единиц: " + str, idx + 1); } }
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(); }
static { points = Collections.synchronizedList(new ArrayList<DrawObject>()); lines = Collections.synchronizedList(new ArrayList<DrawObject>()); ovals = Collections.synchronizedList(new ArrayList<DrawObject>()); rectangles = Collections.synchronizedList(new ArrayList<DrawObject>()); images = Collections.synchronizedList(new ArrayList<DrawObject>()); labels = Collections.synchronizedList(new ArrayList<DrawObject>()); scribbles = Collections.synchronizedList(new ArrayList<DrawObject>()); eqnLines = Collections.synchronizedList(new ArrayList<DrawObject>()); animPoints = Collections.synchronizedList(new ArrayList<DrawObject>()); animLines = Collections.synchronizedList(new ArrayList<DrawObject>()); animOvals = Collections.synchronizedList(new ArrayList<DrawObject>()); animRectangles = Collections.synchronizedList(new ArrayList<DrawObject>()); animLabels = Collections.synchronizedList(new ArrayList<DrawObject>()); df.setMaximumFractionDigits(4); }
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)); } }
void print(String name, double value) { g.drawString(name + ":" + df.format(value), x, y += 20); }
public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; RenderingHints rh = g2d.getRenderingHints(); rh.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHints(rh); // Background. D = this.getSize(); g.setColor(backgroundColor); g.fillRect(0, 0, D.width, D.height); Graphics2D g2 = (Graphics2D) g; g2.setStroke(lineStroke); // Axes, bounding box. g.setColor(Color.gray); g.drawLine(inset, D.height - inset, D.width - inset, D.height - inset); g.drawLine(D.width - inset, inset, D.width - inset, D.height - inset); g.drawLine(inset, inset, inset, D.height - inset); g.drawLine(inset, inset, D.width - inset, inset); double xDelta = (maxX - minX) / numIntervals; // X-ticks and labels. for (int i = 1; i <= numIntervals; i++) { double xTickd = i * xDelta; int xTick = (int) (xTickd / (maxX - minX) * (D.width - 2 * inset)); g.drawLine(inset + xTick, D.height - inset - 5, inset + xTick, D.height - inset + 5); double x = minX + i * xDelta; g.drawString(df.format(x), xTick + inset - 5, D.height - inset + 20); } // Y-ticks double yDelta = (maxY - minY) / numIntervals; for (int i = 0; i < numIntervals; i++) { int yTick = (i + 1) * (int) ((D.height - 2 * inset) / (double) numIntervals); g.drawLine(inset - 5, D.height - yTick - inset, inset + 5, D.height - yTick - inset); double y = minY + (i + 1) * yDelta; g.drawString(df.format(y), 1, D.height - yTick - inset); } // Zoom+move Font savedFont = g.getFont(); g.setFont(plusFont); g.drawString("+", D.width - 25, 20); g.setFont(minusFont); g.drawString("-", D.width - 25, 50); drawArrow(g2d, D.width - 70, 20, D.width - 70, 0, 1.0f, lineStroke); // Up drawArrow(g2d, D.width - 70, 30, D.width - 70, 50, 1.0f, lineStroke); // Down drawArrow(g2d, D.width - 65, 25, D.width - 45, 25, 1.0f, lineStroke); // Right drawArrow(g2d, D.width - 75, 25, D.width - 95, 25, 1.0f, lineStroke); // Left g.setFont(savedFont); // See if standard axes are in the middle. g.setColor(Color.gray); if ((minX < 0) && (maxX > 0) && (drawMiddleAxes)) { // Draw y-axis int x = (int) ((0 - minX) / (maxX - minX) * (D.width - 2 * inset)); g.drawLine(inset + x, D.height - inset, inset + x, inset); } if ((minY < 0) && (maxY > 0) && (drawMiddleAxes)) { // Draw x-axis int y = (int) ((0 - minY) / (maxY - minY) * (D.height - 2.0 * inset)); g.drawLine(inset, D.height - y - inset, D.width - inset, D.height - y - inset); } // Draw the objects. drawObjects(g, points, lines, ovals, rectangles, images, labels, eqnLines); if (animationMode) { drawObjects(g, animPoints, animLines, animOvals, animRectangles, null, labels, eqnLines); // No images in animation mode. } drawScribbles(g); }
public static void writeTopValue(double v) { writeTopString("" + df.format(v)); }
private double test(List baseline, List preferred, List gold) { double bs = 0, ps = 0; if (stat.toUpperCase().equals("F1")) { bs = new Evaluator(gold, baseline).getF1(); ps = new Evaluator(gold, preferred).getF1(); } else if (stat.toUpperCase().equals("P")) { bs = new Evaluator(gold, baseline).getPrecision(); ps = new Evaluator(gold, preferred).getPrecision(); } else if (stat.toUpperCase().equals("R")) { bs = new Evaluator(gold, baseline).getRecall(); ps = new Evaluator(gold, preferred).getRecall(); } double d = Math.abs(ps - bs); double mean = 0; double variance = 0; double sum = 0; double ssum = 0; logger.info( stat + ": original score bs, ps,d: " + formatter.format(bs * 100) + "%, " + formatter.format(ps * 100) + "%, " + formatter.format(d * 100) + "%"); // p - p-value. In general, the lowest the p-value, // the less probable it is that that the null // hypothesis holds. That is, the two systems are // are significantly different. double p = 0; // c - number of times that the pseudostatistic is // greater or equal to the true statistic int c = 0; for (int i = 0; i < iterations; i++) { List baselineCopy = copy(baseline); List preferredCopy = copy(preferred); swap(baselineCopy, preferredCopy, new Random(i * 27)); if (stat.toUpperCase().equals("F1")) { bs = new Evaluator(gold, baselineCopy).getF1(); ps = new Evaluator(gold, preferredCopy).getF1(); } else if (stat.toUpperCase().equals("P")) { bs = new Evaluator(gold, baselineCopy).getPrecision(); ps = new Evaluator(gold, preferredCopy).getPrecision(); } else if (stat.toUpperCase().equals("R")) { bs = new Evaluator(gold, baselineCopy).getRecall(); ps = new Evaluator(gold, preferredCopy).getRecall(); } double di = Math.abs(ps - bs); sum += di; ssum += Math.pow(di, 2); if (di >= d) { c++; // logger.info("score at " + i + " c, bs, ps,d: " + c + ", " + formatter.format(bs * 100) + // "%, " + formatter.format(ps * 100) + "%, " + formatter.format(di * 100) + "%, (" + // formatter.format(d * 100) + "%)"); } } // end for i mean = sum / iterations; variance = (iterations * ssum - Math.pow(sum, 2)) / iterations * (iterations - 1); p = (double) (c + 1) / (iterations + 1); logger.info("mean " + formatter.format(mean) + ", " + formatter.format(Math.sqrt(variance))); logger.info(p + " = (" + c + " + 1) / (" + iterations + " + 1)"); return p; } // end test
private static String time() { float now = (float) (System.currentTimeMillis() - startTime) / 1000; return TIME_FORMAT.format(now); }
static { byteFormat.setMinimumIntegerDigits(3); }
public void parse(Path file) throws IOException { clear(); try (BufferedReader inp = Files.newBufferedReader(file)) { String line; while ((line = inp.readLine()) != null) { if (line.startsWith("Cpu ")) { PerfKey key = new PerfKey(); PerfData data = new PerfData(); // Cpu 0 NSE-AB Init Lock Pgs 19 Mem Pages 4194304 key.cpu = Integer.parseInt(line.substring(4, 6).trim()); data.memPages = Integer.parseInt(line.substring(62).trim()); line = inp.readLine(); // Memory MB 65536 PCBs 12100 Pg Size 16384 Bytes if (line == null || !line.startsWith("Memory MB")) { throw new IOException("Строка должна начинаться с 'Memory MB': " + line); } line = inp.readLine(); // IPUs 4 if (line == null || !line.startsWith("IPUs")) { throw new IOException("Строка должна начинаться с 'IPUs': " + line); } line = inp.readLine(); // Format Version: H07 Data Version: H07 Subsystem Version: 3 if (line == null || !line.startsWith("Format Version:")) { throw new IOException("Строка должна начинаться с 'Format Version:': " + line); } line = inp.readLine(); // Local System \KHAFE1 From 1 Oct 2016, 0:00:01 For 5.1 Minutes if (line == null || !line.startsWith("Local System")) { throw new IOException("Строка должна начинаться с 'Local System:': " + line); } key.system = line.substring(13, 21).trim(); String str = line.substring(28, 49); try { key.date = DATETIME_SDF.parse(str); data.duration = parseDuration(line.substring(56).trim()); } catch (ParseException e) { throw new IOException( "Ошибка декодирования строки (Позиция. " + e.getErrorOffset() + "): " + str + ". Строка:" + line, e); } catch (NumberFormatException e) { throw new IOException("Ошибка декодирования строки : " + str + ". Строка:" + line, e); } line = inp.readLine(); // ---------------------------------------------------------------------------- if (line == null || !line.startsWith("---------")) { throw new IOException("Строка должна начинаться с '---------:': " + line); } line = inp.readLine(); // Cpu-Busy-Time 79.99 % Dispatches 115,637 /s if (line == null || !line.startsWith("Cpu-Busy-Time")) { throw new IOException("Строка должна начинаться с 'Cpu-Busy-Time': " + line); } str = line.substring(25, 33).trim(); try { data.cpuBusyTime = DF.parse(str).floatValue(); } catch (ParseException e) { throw new IOException("Ошибка декодирования Cpu-Busy-Time: " + str, e); } line = inp.readLine(); // Cpu-Qtime 13.89 AQL Intr-Busy-Time 14.41 % if (line == null || !line.startsWith("Cpu-Qtime")) { throw new IOException("Строка должна начинаться с 'Cpu-Qtime': " + line); } line = inp.readLine(); // Starting-Free-Mem 3,267,922 # Ending-Free-Mem 3,267,951 # if (line == null || !line.startsWith("Starting-Free-Mem")) { throw new IOException("Строка должна начинаться с 'Starting-Free-Mem': " + line); } str = line.substring(55, 73).trim(); try { data.endingFreeMem = DF.parse(str).intValue(); } catch (ParseException e) { throw new IOException("Ошибка декодирования Ending-Free-Mem: " + str, e); } line = inp.readLine(); // Swaps 1.10 /s Page-Requests 2.19 /s if (line == null || !line.startsWith("Swaps")) { throw new IOException("Строка должна начинаться с 'Swaps': " + line); } line = inp.readLine(); // Disc-IOs 49.79 /s Cache-Hits 946.87 /s if (line == null || !line.startsWith("Disc-IOs")) { throw new IOException("Строка должна начинаться с 'Disc-IOs': " + line); } this.stat.addPerfData(key, data); } } } }
void print(String name, Vec value) { g.drawString(name + ":" + df.format(value.x) + " , " + df.format(value.y), x, y += 20); }
/** 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)); } }
static { DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator('.'); symbols.setGroupingSeparator(','); DF.setDecimalFormatSymbols(symbols); }