List of usage examples for java.util Formatter format
public Formatter format(String format, Object... args)
From source file:fll.scheduler.SchedulerUI.java
/** * Run the scheduler and optionally the table optimizer. */// ww w . j av a2s. c o m private void runScheduler() { try { saveScheduleDescription(); final SchedulerWorker worker = new SchedulerWorker(); // make sure the task doesn't start until the window is up _progressDialog.addComponentListener(new ComponentAdapter() { @Override public void componentShown(final ComponentEvent e) { _progressDialog.removeComponentListener(this); worker.execute(); } }); _progressDialog.setLocationRelativeTo(SchedulerUI.this); _progressDialog.setNote("Running Scheduler"); _progressDialog.setVisible(true); } catch (final IOException e) { final Formatter errorFormatter = new Formatter(); errorFormatter.format("Error reading description file: %s", e.getMessage()); LOGGER.error(errorFormatter, e); JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error Running Scheduler", JOptionPane.ERROR_MESSAGE); } catch (final ParseException e) { final Formatter errorFormatter = new Formatter(); errorFormatter.format("Error parsing description file: %s", e.getMessage()); LOGGER.error(errorFormatter, e); JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error Running Scheduler", JOptionPane.ERROR_MESSAGE); } catch (final InvalidParametersException e) { LOGGER.error(e.getMessage(), e); JOptionPane.showMessageDialog(SchedulerUI.this, e.getMessage(), "Error Running Scheduler", JOptionPane.ERROR_MESSAGE); } }
From source file:org.kalypso.kalypsomodel1d2d.conv.SWANAdditionalDataConverter.java
private void writeCurrentSeriesFile(final Date pDate, final FileObject modelCurrentFileSerie) { Formatter lFormatterCurrent = null; // put first the Y component of current into buffer to write it out after X-component according to SWAN formating // rules/*from www. j ava 2 s. c om*/ final StringBuffer lStrBuffY = new StringBuffer(); try { final List<INodeResult> lListActResults = m_resultsSimpleHandler.getResultsForDate(pDate); lFormatterCurrent = new Formatter(modelCurrentFileSerie.getContent().getOutputStream(), Charset.defaultCharset().name(), Locale.US); if (lListActResults == null) { // TODO: debug output... return; } final double lDoubleExclNr = Double.parseDouble(ISimulation1D2DConstants.SIM_SWAN_EXCLUSION_NUMBER); for (final INodeResult lResultAct : lListActResults) { if (lDoubleExclNr != lResultAct.getWaterlevel()) { try { final List<Double> lListDoubleVelocity = lResultAct.getVelocity();// AbsoluteVelocity(); lFormatterCurrent.format("%.2f\n", lListDoubleVelocity.get(0)); //$NON-NLS-1$ lStrBuffY.append(String.format(Locale.US, "%.2f\n", lListDoubleVelocity.get(1))); //$NON-NLS-1$ } catch (final Exception e) { lFormatterCurrent.format("%s\n", m_strDefaulCurrentValue); //$NON-NLS-1$ lStrBuffY.append(String.format(Locale.US, "%s\n", m_strDefaulCurrentValue)); //$NON-NLS-1$ } } else { lFormatterCurrent.format("%s\n", m_strDefaulCurrentValue); //$NON-NLS-1$ lStrBuffY.append(String.format(Locale.US, "%s\n", m_strDefaulCurrentValue)); //$NON-NLS-1$ } } lFormatterCurrent.format("%s\n", lStrBuffY.toString()); //$NON-NLS-1$ FormatterUtils.checkIoException(lFormatterCurrent); } catch (final Exception e) { e.printStackTrace(); } finally { if (lFormatterCurrent != null) { // REMARK: do not check io-exception here, else other exception would be hidden by this on lFormatterCurrent.close(); } } }
From source file:edu.ku.brc.af.ui.forms.formatters.DataObjFieldFormatMgr.java
/** * Format a data object using a named formatter * @param dataObj the data object for which fields will be formatted for it * @return the string result of the format */// ww w .ja v a 2 s . c om protected String formatInternal(final DataObjDataFieldFormat format, final Object[] dataObjs) { if (format != null) { DataObjectGettable getter = DataObjectGettableFactory.get(format.getDataClass().getName(), FormHelper.DATA_OBJ_GETTER); if (getter != null) { StringBuilder strBuf = new StringBuilder(128); if (dataObjs.length == format.getFields().length) { int inx = 0; for (DataObjDataField field : format.getFields()) { Object value = dataObjs[inx++]; if (value != null) { if (field.getDataObjFormatterName() != null) { String fmtStr = formatInternal( getDataFormatter(value, field.getDataObjFormatterName()), value); if (fmtStr != null) { strBuf.append(fmtStr); } } else if (field.getUiFieldFormatterName() != null) { UIFieldFormatterIFace fmt = UIFieldFormatterMgr.getInstance() .getFormatter(field.getUiFieldFormatterName()); if (fmt != null) { strBuf.append(fmt.formatToUI(value)); } else { strBuf.append(value); } } else if (value.getClass() == field.getType()) { // When format is null then it is a string if (field.getType() == String.class && (field.getFormat() == null || format.equals("%s"))) { if (field.getSep() != null) { strBuf.append(field.getSep()); } strBuf.append(value.toString()); } else { Object[] arg = { value }; Formatter formatter = new Formatter(); formatter.format(format.getFormat(), arg); strBuf.append(formatter.toString()); } } else { log.error("Mismatch of types data retrieved as class[" + value.getClass().getSimpleName() + "] and the format requires [" + field.getType().getSimpleName() + "]"); } } } } else { log.error("Data Array sent to formatter is not the same length [" + dataObjs.length + "] as the formatter [" + format.getFields().length + "]"); } return strBuf.toString(); } } return ""; }
From source file:com.itemanalysis.psychometrics.cfa.CfaSummary.java
public String multipleCfa(int estimationMethod, int optimizationMethod) { StringBuilder sb = new StringBuilder(); Formatter f = new Formatter(sb); ConfirmatoryFactorAnalysis congeneric = new ConfirmatoryFactorAnalysis(cfaMatrix, numberOfExaminees, ConfirmatoryFactorAnalysisModel.CONGENERIC, estimationMethod); congeneric.optimize(optimizationMethod); logger.info("Congeneric Model CFA completed\n" + congeneric.printOptimizationSummary()); ConfirmatoryFactorAnalysis tauEquivalent = new ConfirmatoryFactorAnalysis(cfaMatrix, numberOfExaminees, ConfirmatoryFactorAnalysisModel.TAU_EQUIVALENT, estimationMethod); tauEquivalent.optimize(optimizationMethod); logger.info("Tau-equivalent Model CFA completed\n" + tauEquivalent.printOptimizationSummary()); ConfirmatoryFactorAnalysis parallel = new ConfirmatoryFactorAnalysis(cfaMatrix, numberOfExaminees, ConfirmatoryFactorAnalysisModel.PARALLEL, estimationMethod); parallel.optimize(optimizationMethod); logger.info("Parallel Model CFA completed\n" + parallel.printOptimizationSummary()); f.format("%-60s", " CONGENERIC, TAU-EQUIVALENT, AND PARALLEL"); f.format("%n"); f.format("%-60s", " CONFIRMATORY FACTOR ANLAYSIS"); f.format("%n"); f.format("%n"); f.format("%n"); f.format("%-60s", " ****CAUTION CONFIRMATORY FACTOR ANALYSIS IS STILL IN DEVELOPMENT****"); f.format("%n"); f.format("%-60s", " ****IT HAS NOT BEEN THOROUGHLY TESTED****"); f.format("%n"); f.format("%n"); f.format("%-25s", " MODEL SUMMARY"); f.format("%n"); f.format("%-60s", "================================================================="); f.format("%n"); f.format("%11s", "Statistic"); f.format("%5s", ""); f.format("%10s", "Congeneric"); f.format("%5s", ""); f.format("%14s", "Tau-Equivalent"); f.format("%5s", ""); f.format("%10s", "Parallel"); f.format("%n"); f.format("%-60s", "-----------------------------------------------------------------"); f.format("%n"); f.format("%11s", "Fmin"); f.format("%5s", ""); f.format("% 10.4f", congeneric.getEstimator().fMin()); f.format("%5s", ""); f.format("% 10.4f", tauEquivalent.getEstimator().fMin()); f.format("%9s", ""); f.format("% 10.4f", parallel.getEstimator().fMin()); f.format("%n"); f.format("%11s", "Chi^2"); f.format("%5s", ""); f.format("% 10.4f", congeneric.getEstimator().chisquare()); f.format("%5s", ""); f.format("% 10.4f", tauEquivalent.getEstimator().chisquare()); f.format("%9s", ""); f.format("% 10.4f", parallel.getEstimator().chisquare()); f.format("%n"); f.format("%11s", "df"); f.format("%5s", ""); f.format("% 10.4f", congeneric.getEstimator().degreesOfFreedom()); f.format("%5s", ""); f.format("% 10.4f", tauEquivalent.getEstimator().degreesOfFreedom()); f.format("%9s", ""); f.format("% 10.4f", parallel.getEstimator().degreesOfFreedom()); f.format("%n"); f.format("%11s", "p-rho"); f.format("%5s", ""); f.format("% 10.4f", congeneric.getEstimator().pvalue()); f.format("%5s", ""); f.format("% 10.4f", tauEquivalent.getEstimator().pvalue()); f.format("%9s", ""); f.format("% 10.4f", parallel.getEstimator().pvalue()); f.format("%n"); f.format("%11s", "GFI"); f.format("%5s", ""); f.format("% 10.4f", congeneric.getEstimator().gfi()); f.format("%5s", ""); f.format("% 10.4f", tauEquivalent.getEstimator().gfi()); f.format("%9s", ""); f.format("% 10.4f", parallel.getEstimator().gfi()); f.format("%n"); f.format("%11s", "AGFI"); f.format("%5s", ""); f.format("% 10.4f", congeneric.getEstimator().agfi()); f.format("%5s", ""); f.format("% 10.4f", tauEquivalent.getEstimator().agfi()); f.format("%9s", ""); f.format("% 10.4f", parallel.getEstimator().agfi()); f.format("%n"); f.format("%11s", "RMR"); f.format("%5s", ""); f.format("% 10.4f", Math.sqrt(congeneric.getEstimator().meanSquaredResidual())); f.format("%5s", ""); f.format("% 10.4f", Math.sqrt(tauEquivalent.getEstimator().meanSquaredResidual())); f.format("%9s", ""); f.format("% 10.4f", Math.sqrt(parallel.getEstimator().meanSquaredResidual())); f.format("%n"); f.format("%11s", "RMSEA"); f.format("%5s", ""); f.format("% 10.4f", congeneric.getEstimator().rmsea()); f.format("%5s", ""); f.format("% 10.4f", tauEquivalent.getEstimator().rmsea()); f.format("%9s", ""); f.format("% 10.4f", parallel.getEstimator().rmsea()); f.format("%n"); f.format("%11s", "Reliability"); f.format("%5s", ""); f.format("% 10.4f", congeneric.getEstimator().mcdonaldOmega()); f.format("%5s", ""); f.format("% 10.4f", tauEquivalent.getEstimator().mcdonaldOmega()); f.format("%9s", ""); f.format("% 10.4f", parallel.getEstimator().mcdonaldOmega()); f.format("%n"); f.format("%-60s", "-----------------------------------------------------------------"); f.format("%n"); f.format("%n"); f.format("%n"); f.format("%n"); sb.append(congeneric.getEstimator().printEstimates(items)); f.format("%n"); f.format("%n"); f.format("%n"); sb.append(tauEquivalent.getEstimator().printEstimates(items)); f.format("%n"); f.format("%n"); f.format("%n"); sb.append(parallel.getEstimator().printEstimates(items)); f.format("%n"); f.format("%n"); return f.toString(); }
From source file:fll.scheduler.SchedulerUI.java
void saveScheduleDescription() { if (null == mScheduleDescriptionFile) { // prompt the user for a filename to save to final String startingDirectory = PREFS.get(DESCRIPTION_STARTING_DIRECTORY_PREF, null); final JFileChooser fileChooser = new JFileChooser(); final FileFilter filter = new BasicFileFilter("FLL Schedule Description (properties)", new String[] { "properties" }); fileChooser.setFileFilter(filter); if (null != startingDirectory) { fileChooser.setCurrentDirectory(new File(startingDirectory)); }/*from www . j ava 2 s. c o m*/ final int returnVal = fileChooser.showSaveDialog(SchedulerUI.this); if (returnVal == JFileChooser.APPROVE_OPTION) { final File currentDirectory = fileChooser.getCurrentDirectory(); PREFS.put(DESCRIPTION_STARTING_DIRECTORY_PREF, currentDirectory.getAbsolutePath()); mScheduleDescriptionFile = fileChooser.getSelectedFile(); mDescriptionFilename.setText(mScheduleDescriptionFile.getName()); } else { // user canceled return; } } try (final Writer writer = new OutputStreamWriter(new FileOutputStream(mScheduleDescriptionFile), Utilities.DEFAULT_CHARSET)) { final SolverParams params = mScheduleDescriptionEditor.getParams(); final List<String> errors = params.isValid(); if (!errors.isEmpty()) { final String formattedErrors = errors.stream().collect(Collectors.joining("\n")); JOptionPane.showMessageDialog(SchedulerUI.this, "There are errors that need to be corrected before the description can be saved: " + formattedErrors, "Error saving file", JOptionPane.ERROR_MESSAGE); } else { final Properties properties = new Properties(); params.save(properties); properties.store(writer, null); } } catch (final IOException e) { final Formatter errorFormatter = new Formatter(); errorFormatter.format("Error saving file: %s", e.getMessage()); LOGGER.error(errorFormatter, e); JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error saving file", JOptionPane.ERROR_MESSAGE); } }
From source file:org.kalypso.kalypsomodel1d2d.conv.Control1D2DConverterSWAN.java
/** * writes the initial condition into the SWAN-Kalypso controlFile (INPUT) *//*w w w . j a v a 2s .c o m*/ private void formateInitLine(final Formatter formatter) { // //format the currents final Integer lInitVal = m_controlModel.getINITialValuesSWAN(); String lStrInitVal = INIT_DEF; final String lStrInitPAR = ""; //$NON-NLS-1$ switch (lInitVal) { case 0: lStrInitVal = INIT_DEF; break; case 1: lStrInitVal = INIT_ZERO; break; case 2: lStrInitVal = INIT_PAR + m_controlModel.getINITialValuesParSWAN(); break; case 3: lStrInitVal = INIT_HOT + SINGLE + ISimulation1D2DConstants.SIM_SWAN_HOT_FILE; break; default: lStrInitVal = INIT_DEF; } formatter.format("INIT %s", lStrInitVal); //$NON-NLS-1$ if (!"".equals(lStrInitPAR)) //$NON-NLS-1$ { formatter.format(" %s", lStrInitPAR); //$NON-NLS-1$ } formatter.format("\n"); //$NON-NLS-1$ }
From source file:edu.ku.brc.af.ui.forms.formatters.DataObjFieldFormatMgr.java
/** * Format a data object using a named formatter * @param dataObj the data object for which fields will be formatted for it * @return the string result of the format *//*from w w w . j a v a 2 s . c om*/ protected String formatInternal(final DataObjDataFieldFormatIFace format, final Object dataObj) { String restricted = FormHelper.checkForRestrictedValue(dataObj); if (restricted != null) { return restricted; } if (format != null) { if (format.isDirectFormatter()) { return format.format(dataObj); } DataObjectGettable getter = DataObjectGettableFactory.get(format.getDataClass().getName(), FormHelper.DATA_OBJ_GETTER); if (getter != null) { StringBuilder strBuf = new StringBuilder(128); for (DataObjDataField field : format.getFields()) { Class<?> fieldClass = field.getType(); Object[] values = getFieldValues(new String[] { field.getName() }, dataObj, getter); Object value = values != null ? values[0] : null; // NOTE: if the field was a Date or Calendar object it has already been reformatted to a String // so we change the fieldClass to string so everything works out. if (fieldClass == Date.class || fieldClass == Calendar.class) { fieldClass = String.class; } if (value != null) { if (AppContextMgr.isSecurityOn() && value instanceof FormDataObjIFace) { DBTableInfo tblInfo = DBTableIdMgr.getInstance() .getByShortClassName(value.getClass().getSimpleName()); if (tblInfo != null) { PermissionSettings perm = tblInfo.getPermissions(); if (perm != null) { if (!perm.canView()) { return ""; } } } } if (field.getDataObjFormatterName() != null) { String fmtStr = formatInternal(getDataFormatter(value, field.getDataObjFormatterName()), value); if (fmtStr != null) { strBuf.append(fmtStr); } } else if (field.getUiFieldFormatterName() != null) { UIFieldFormatterIFace fmt = UIFieldFormatterMgr.getInstance() .getFormatter(field.getUiFieldFormatterName()); DBTableInfo tblInfo = DBTableIdMgr.getInstance() .getByShortClassName(dataObj.getClass().getSimpleName()); if (tblInfo != null) { DBFieldInfo fi = tblInfo.getFieldByName(field.getName()); if (fi != null && fi.getFormatter() != null) { fmt = fi.getFormatter(); } } if (fmt != null) { strBuf.append(fmt.formatToUI(value)); } else { strBuf.append(value); } } else if (value.getClass() == fieldClass) { // When format is null then it is a string if (fieldClass == String.class && (field.getFormat() == null || format.equals("%s"))) { if (field.getSep() != null) { strBuf.append(field.getSep()); } strBuf.append(value.toString()); } else { String sep = field.getSep(); if (sep != null) { strBuf.append(sep); } //log.debug("["+value+"]["+format+"]"); if (field.getFormat() != null) { Object[] arg = { value }; Formatter formatter = new Formatter(); formatter.format(field.getFormat(), arg); strBuf.append(formatter.toString()); } else { strBuf.append(value.toString()); } } } else { log.error("Mismatch of types data retrieved as class[" + (value != null ? value.getClass().getSimpleName() : "N/A") + "] and the format requires [" + (field != null ? (fieldClass != null ? fieldClass.getSimpleName() : "N/A 2") : "N/A") + "]"); } } } return strBuf.toString(); } } return ""; }
From source file:org.kalypso.kalypsomodel1d2d.conv.Control1D2DConverter.java
/** * writes out the time steps. <BR> * IMPORTANT: we write the dates in the time zone according to the kalypso-preferences! *///from www. j a v a 2s . co m private void writeTimeStep(final Formatter formatter, final String message, final Calendar calculationStep, final Calendar lastStepCal, final String uRVal, final int niti) throws CoreException, IOException { final String dashes = StringUtils.repeat("-", message.length()); //$NON-NLS-1$ formatter.format("com %s%n", dashes); //$NON-NLS-1$ formatter.format("com %s%n", message); //$NON-NLS-1$ formatter.format("com %s%n", dashes); //$NON-NLS-1$ final long timeStepInterval; final double timeStepMinutes; final int year; final int dayOfYear; final double ihre; final TimeZone displayTimeZone = KalypsoCorePlugin.getDefault().getTimeZone(); Calendar kalypsoCalendarStep = Calendar.getInstance(displayTimeZone); // unsteady if (calculationStep != null) { // REMARK: we write the date in the kalypso-preferences time zone! kalypsoCalendarStep.setTime(calculationStep.getTime()); dayOfYear = kalypsoCalendarStep.get(Calendar.DAY_OF_YEAR); year = kalypsoCalendarStep.get(Calendar.YEAR); // REMARK: we write the date in the kalypso-preferences time zone! final Calendar kalypsoCallendarPreviousStep = Calendar.getInstance(displayTimeZone); kalypsoCallendarPreviousStep.setTime(lastStepCal.getTime()); timeStepInterval = kalypsoCalendarStep.getTimeInMillis() - kalypsoCallendarPreviousStep.getTimeInMillis(); // FIXME: should never happen, kalypso does not allow summertime timezones any more // if timeStepInterval is zero, step will be ignored // (this will happen on summertime to wintertime transition) if (timeStepInterval == 0) { formatter.format(Messages.getString("org.kalypso.kalypsomodel1d2d.conv.Control1D2DConverter.14")); //$NON-NLS-1$ return; } timeStepMinutes = (double) timeStepInterval / (60 * 1000); ihre = getTimeInPercentage(kalypsoCalendarStep); } // steady dont need startdate else { kalypsoCalendarStep = null; dayOfYear = 0; year = 0; timeStepMinutes = 0; ihre = 0; } formatter.format("DT MIN %e%8d%8d%8.2f", timeStepMinutes, year, dayOfYear, ihre); //$NON-NLS-1$ // BC lines if (niti == 0) formatter.format("%nBC%n"); //$NON-NLS-1$ else formatBC(formatter, uRVal, niti); // order is important, first QC than HC, SQC and EFE formatBoundCondLines(formatter, kalypsoCalendarStep, Kalypso1D2DDictConstants.DICT_COMPONENT_TIME, Kalypso1D2DDictConstants.DICT_COMPONENT_DISCHARGE); formatBoundCondLines(formatter, kalypsoCalendarStep, Kalypso1D2DDictConstants.DICT_COMPONENT_TIME, Kalypso1D2DDictConstants.DICT_COMPONENT_WATERLEVEL); formatBoundCondLines(formatter, kalypsoCalendarStep, Kalypso1D2DDictConstants.DICT_COMPONENT_WATERLEVEL, Kalypso1D2DDictConstants.DICT_COMPONENT_DISCHARGE); FormatterUtils.checkIoException(formatter); for (final Map.Entry<Integer, IFlowRelationship> buildingData : m_buildingProvider.getBuildingData() .entrySet()) { final Integer buildingID = buildingData.getKey(); final IFlowRelationship building = buildingData.getValue(); final int buildingKind = 10; int lIntDirection = 0; if (building instanceof IBuildingFlowRelation) { if (((IBuildingFlowRelation) building).getKind() != KIND.TABULAR) { final String msg = Messages.getString( "org.kalypso.kalypsomodel1d2d.conv.Control1D2DConverter.43", //$NON-NLS-1$ ((IBuildingFlowRelation) building).getKind()); throw new CoreException(new Status(IStatus.ERROR, KalypsoModel1D2DPlugin.PLUGIN_ID, msg)); } lIntDirection = ((IBuildingFlowRelation) building).getDirection(); } else if (building instanceof IBuildingFlowRelation2D) { if (((IBuildingFlowRelation2D) building).getKind() != KIND2D.TABULAR) { final String msg = Messages.getString( "org.kalypso.kalypsomodel1d2d.conv.Control1D2DConverter.43", //$NON-NLS-1$ ((IBuildingFlowRelation) building).getKind()); throw new CoreException(new Status(IStatus.ERROR, KalypsoModel1D2DPlugin.PLUGIN_ID, msg)); } lIntDirection = ((IBuildingFlowRelation2D) building).getDirection(); } final double direction = Math.toRadians(lIntDirection); formatter.format("FC%14d%8d%8.3f%8.3f%8.3f%8.3f%8.3f%n", buildingID, buildingKind, 0.0, 0.0, 0.0, 0.0, //$NON-NLS-1$ direction); FormatterUtils.checkIoException(formatter); } formatBoundCondLines(formatter, kalypsoCalendarStep, Kalypso1D2DDictConstants.DICT_COMPONENT_TIME, Kalypso1D2DDictConstants.DICT_COMPONENT_SPECIFIC_DISCHARGE_1D); formatBoundCondLines(formatter, kalypsoCalendarStep, Kalypso1D2DDictConstants.DICT_COMPONENT_TIME, Kalypso1D2DDictConstants.DICT_COMPONENT_SPECIFIC_DISCHARGE_2D); // add other conti lines types as well (buildings)? if (m_controlModel.getHasWindDrag() && !m_boolPrintWindLineDone) { formatter.format("WVA 1.0 1.0 1%n"); //$NON-NLS-1$ m_boolPrintWindLineDone = true; } formatter.format("ENDSTEP %s%n", message); //$NON-NLS-1$ FormatterUtils.checkIoException(formatter); }
From source file:com.itemanalysis.psychometrics.irt.model.Irm3PL.java
/** * A string representation of the item parameters. Mainly used for printing and debugging. * * @return a string of item parameters./*from w w w . j a v a 2 s . co m*/ */ @Override public String toString() { StringBuilder sb = new StringBuilder(); Formatter f = new Formatter(sb); String name = getName().toString(); if (getName() != null) { name = getName().toString().substring(0, Math.min(18, name.length())); } else { name = ""; } f.format("%-18s", name); f.format("%2s", ""); String m = ""; if (numberOfParameters == 3) { m = "L3"; } else if (numberOfParameters == 2) { m = "L2"; } else { m = "L1"; } f.format("%-3s", m); f.format("%4s", ""); f.format("% 4.2f", getDiscrimination()); f.format("%1s", ""); f.format("(%4.2f)", getDiscriminationStdError()); f.format("%4s", ""); f.format("% 4.2f", getDifficulty()); f.format("%1s", ""); f.format("(%4.2f)", getDifficultyStdError()); f.format("%4s", ""); if ((numberOfParameters < 3 && getGuessing() > 0) || numberOfParameters == 3) { f.format("% 4.2f", getGuessing()); f.format("%1s", ""); f.format("(%4.2f)", getGuessingStdError()); f.format("%4s", ""); } else { f.format("%13s", ""); } if (getSlipping() < 1) { f.format("% 4.2f", getSlipping()); f.format("%1s", ""); f.format("(%4.2f)", getSlippingStdError()); f.format("%4s", ""); } return f.toString(); // //OLD================================================================== // String name = ""; // if(getName()!=null){ // name = getName().toString(); // } // // f.format("%10s", name);f.format("%2s", ": "); // f.format("%1s", "["); // f.format("% .6f", getDiscrimination()); f.format("%2s", ", "); // f.format("% .6f", getDifficulty()); f.format("%2s", ", "); // f.format("% .6f", getGuessing()); // // if(getSlipping()<1) { // f.format("%2s", ", "); // f.format("% .6f", getSlipping()); // } // f.format("%1s", "]"); // f.format("%n"); // f.format("%10s", "");f.format("%2s", ""); // f.format("%1s", "("); // f.format("% .6f", getDiscriminationStdError()); f.format("%2s", ", "); // f.format("% .6f", getDifficultyStdError()); f.format("%2s", ", "); // f.format("% .6f", getGuessingStdError()); // if(getSlipping()<1){ // f.format("%2s", ", "); // f.format("% .6f", getSlippingStdError()); // } // f.format("%1s", ")"); // // return f.toString(); }
From source file:com.insprise.common.lang.StringUtilities.java
/** * Returns a properly formatted string representation of the given table (a list of lists of strings). * <p><code><pre>{@code List<List<Object>> lists = new ArrayList<List<Object>>(); * List<Object> list = new ArrayList<Object>(); * list.add("ID");/* w w w . ja v a2 s . co m*/ * list.add("Name"); * list.add("Remarks"); * lists.add(list); * * list = new ArrayList<Object>(); * list.add("A"); * list.add("Jack"); * list.add("Employee group"); * list.add("8"); * lists.add(list); * * System.out.println(StringUtilities.displayTable(lists, true, 10)); * * [Results] * +----+------+------------+-------+ * | ID | Name | Remarks | Score | * +----+------+------------+-------+ * | A | Jack | Employee | 8 | * | | | group | | * +----+------+------------+-------+}</pre></code> * @param table * @param firstRowHeadRead is the first row the head read? * if set to <code>true</code>, a line separator will be inserted after the first line. * @param maxColumnLength the max. length of a column. If the data is longer, it will be wrapped. * @return a properly formatted string representation of the given table (a list of lists of strings). */ public static String displayTable(List<List<Object>> table, boolean firstRowHeadRead, int maxColumnLength) { List<Integer> lengths = new ArrayList<Integer>(); // first, find column length. for (int r = 0; r < table.size(); r++) { // for each row for (int c = 0; table.get(r) != null && c < table.get(r).size(); c++) { // for each col String s = null; if (table.get(r).get(c) != null) { s = table.get(r).get(c).toString(); } Integer oldLength = null; if (lengths.size() > c) { oldLength = lengths.get(c); } else { lengths.add(null); } if (s != null) { if (oldLength == null) { lengths.set(c, Math.min(s.length(), maxColumnLength)); } else { lengths.set(c, Math.min(maxColumnLength, Math.max(s.length(), oldLength))); } } else if (oldLength == null || oldLength == 0) { lengths.set(c, 0); } } } StringBuilder sb = new StringBuilder("\n"); // always starts with a new line to avoid misplacement. Formatter formatter = new Formatter(sb); // ------ starts print separator line. for (int i = 0; i < lengths.size(); i++) { sb.append("+-"); // margin is 2. int colLength = lengths.get(i); for (int j = 0; j < colLength + 1; j++) { sb.append("-"); } } sb.append("+"); // ------ finishes print separator line. HashMap<Integer, String[]> wraps = new HashMap<Integer, String[]>(); // used to contain wraps. for (int r = 0; r < table.size(); r++) { // for each row int rowHeight = 1; wraps.clear(); for (int c = 0; table.get(r) != null && c < table.get(r).size(); c++) { // for each col int colLength = lengths.get(c); if (c == 0) { sb.append("\n"); // first col. } sb.append(c == 0 && (!firstRowHeadRead || (firstRowHeadRead && r != 0)) ? "> " : "| "); String s = null; if (table.get(r).get(c) != null) { s = table.get(r).get(c).toString(); } if (s == null) { formatter.format("%-" + colLength + "s", ""); } else { if (s.length() > colLength) { String[] wrap = wrap(s, colLength, true); rowHeight = Math.max(rowHeight, wrap.length); wraps.put(c, wrap); formatter.format("%-" + colLength + "s", wrap[0]); } else { formatter.format("%-" + (colLength == 0 ? 1 : colLength) + "s", s); } } sb.append(" "); // margin. if (c == table.get(r).size() - 1) { // last row sb.append("|"); } } for (int k = 1; k < rowHeight; k++) { // rowHeight > 1 for (int c = 0; table.get(r) != null && c < table.get(r).size(); c++) { // for each col int colLength = lengths.get(c); if (c == 0) { sb.append("\n"); // first col. } sb.append("| "); String s = null; String[] wrap = wraps.get(c); if (wrap != null && wrap.length > k) { s = wrap[k]; } if (s == null) { formatter.format("%-" + (colLength == 0 ? 1 : colLength) + "s", ""); } else { formatter.format("%-" + colLength + "s", s); } sb.append(" "); // margin. if (c == table.get(r).size() - 1) { // last row sb.append("|"); } } } // end for // rowHeight > 1. if (firstRowHeadRead && r == 0) { // ------ starts print separator line. sb.append("\n"); for (int i = 0; i < lengths.size(); i++) { sb.append("+-"); // margin is 2. int colLength = lengths.get(i); for (int j = 0; j < colLength + 1; j++) { sb.append("-"); } } sb.append("+"); // ------ finishes print separator line. } } // end for each row // ------ starts print separator line. sb.append("\n"); for (int i = 0; i < lengths.size(); i++) { sb.append("+-"); // margin is 2. int colLength = lengths.get(i); for (int j = 0; j < colLength + 1; j++) { sb.append("-"); } } sb.append("+"); // ends // ------ finishes print separator line. return sb.toString(); }