⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 formatuos.java

📁 国外的数据结构与算法分析用书
💻 JAVA
字号:
/* FormatUos.java
 * ---------------------------------------------
 * Copyright (c) 2001 University of Saskatchewan
 * All Rights Reserved
 * --------------------------------------------- */
 
package dslib.base;

import dslib.exception.InvalidArgumentUosException;

/**	A class with two methods to format data into a field of a specified width.
		They are used to align output into columns to facilitate reading it.  */
public class FormatUos
{
	/**	Pad the string representation of `value' to size `width' according to `format'
		`format' must be `c', `l', or `r' for centering, left justified, or right justified.
		Analysis: Time = O(1) */
	public static String pad(int value, int width, char format)
	{
		return pad(new Integer(value), width, format);
	}

	/**	Pad the string representation of `obj' to size `width' according to `format'
		`format' must be `c', `l', or `r' for centering, left justified, or right justified.
		Analysis: Time = O(width - obj.toString().length()) */
	public static String pad(Object obj, int width, char format)
	{
		String result = obj.toString();
		if (format == 'c')
		{
			while (result.length() < width - 1)
				result = " " + result  + " ";
			if (result.length() < width)
				result = result  + " ";
		}
		else if (format == 'l')
			while (result.length() < width)
				result = result  + " ";
		else if (format == 'r')
			while (result.length() < width)
				result = " " + result;
		return result;
	}

	/**	Obtain a String representation of value with d decimal places.
		Analysis: Time = O(d) 
		PRECONDITION:
			d >= 0  */
	public static String withDecimals(double value, int d)
	{
		if ( d < 0)
			throw new InvalidArgumentUosException("Number of decimal places must be >= 0.");
			
		String result = "" + Math.round(value*Math.pow(10,d));
		if (d==0)
			return result;
		else
		{
			while (result.length() < d + 1)
				result = "0" + result;
				
			return result.substring(0, result.length()-d) + "."
					+ result.substring(result.length()-d, result.length()); 	
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -