package ch01; /** * 练习1.3 只使用处理I/O的printDigit方法,编写一种方法以输出任意 * double型量(可以是负数)。 */ public class EX03 { private static void printDigit(int i) { System.out.print(i); } private static void printOut(int n) { if (n >= 10) { printOut(n/10); } printDigit(n%10); } private static void printDouble(double f) { //首先找出负号 if (f < 0) { System.out.print('-'); f = -f; } //找出小数点位置 String value = String.valueOf(f); int intPart = 0, dotPart = 0; int dotPos = value.indexOf('.'); if (dotPos < 0) { intPart = Integer.valueOf(value); printOut(intPart); } else if (dotPos == 0) { intPart = 0; dotPart = Integer.valueOf(value.substring(dotPos+1)); printOut(intPart); System.out.print('.'); printOut(dotPart); } else { intPart = Integer.valueOf(value.substring(0, dotPos)); dotPart = Integer.valueOf(value.substring(dotPos + 1)); printOut(intPart); System.out.print('.'); printOut(dotPart); } System.out.println(); } public static void main(String[] args) { printDouble(10.234); printDouble(-10000.2); printDouble(1000); printDouble(10001.0); printDouble(10001.1456); } }