天天看点

Java经典实例参考文献

3.1分解字符串

String a = "Java is great";
System.out.println(a);
String b = a.substring(5);
System.out.println(b);
String c = a.substring(5, 7);
System.out.println(c);
String d = a.substring(5, a.length());
System.out.println(d);      

3.3字符串分隔连接

//final String SAMPLE_STRING = "Alpha Bravo Charlie";
 final String SAMPLE_STRING = "喜 欢 我";
 StringBuilder sb1 = new StringBuilder();
 for (String word : SAMPLE_STRING.split(" ")) {
     if (sb1.length() > 0) {
         sb1.append(", ");
     }
     sb1.append(word);
 }
 System.out.println(sb1);

 // Method using a StringTokenizer
 StringTokenizer st = new StringTokenizer(SAMPLE_STRING);
 StringBuilder sb2 = new StringBuilder();
 while (st.hasMoreElements()) {
     sb2.append(st.nextToken());
     if (st.hasMoreElements()) {
         sb2.append(", ");
     }
 }
 System.out.println(sb2);      

3.5字符串对齐

public enum Justify {LEFT,CENTER,RIGHT}
private Justify just;
private int maxChars;
public StringAlign(int maxChars, Justify just) {
    switch(just) {
        case LEFT:
        case CENTER:
        case RIGHT:
            this.just = just;
            break;
        default:
            throw new IllegalArgumentException("invalid justification arg.");
    }
    if (maxChars < 0) {
        throw new IllegalArgumentException("maxChars must be positive.");
    }
    this.maxChars = maxChars;
}
@Override
public StringBuffer format(
        Object input, StringBuffer where, FieldPosition ignore)  {

    String s = input.toString();
    String wanted = s.substring(0, Math.min(s.length(), maxChars));
    switch (just) {
        case RIGHT:
            pad(where, maxChars - wanted.length());
            where.append(wanted);
            break;
        case CENTER:
            int toAdd = maxChars - wanted.length();
            pad(where, toAdd/2);
            where.append(wanted);
            pad(where, toAdd - toAdd/2);
            break;
        case LEFT:
            where.append(wanted);
            pad(where, maxChars - wanted.length());
            break;
    }
    return where;
}
protected final void pad(StringBuffer to, int howMany) {
    for (int i=0; i<howMany; i++)
        to.append(' ');
}
String format(String s) {
    return format(s, new StringBuffer(), null).toString();
}
public Object parseObject (String source, ParsePosition pos)  {
    return source;
}
public static void main(String[] args) {
    System.out.println(new StringAlign(150,Justify.RIGHT).format("String Align"));
}      

3.6Unicode字符和String之间的转换

StringBuilder b = new StringBuilder();
for (char c = 'a'; c<'d'; c++) {
    b.append(c);
}
b.append('\u00a5');
b.append('\u01FC');
b.append('\u0391');
b.append('\u03A9');
for (int i=0; i<b.length(); i++) {
    System.out.printf(
            "Character #%d (%04x) is %c%n",
            i, (int)b.charAt(i), b.charAt(i));
}
System.out.println("Accumulated characters are " + b);      

3.7字符串颠倒

String s = "烦 躁";
Stack<String> myStack = new Stack<>();
StringTokenizer st = new StringTokenizer(s);
st.countTokens();
while (st.hasMoreTokens()) {
    myStack.push(st.nextToken());
}
System.out.print('"' + s + '"' + "\n backwards by word is:\n\t\"");
while (!myStack.empty()) {
    System.out.print(myStack.pop());
    System.out.print(' ');
}
System.out.println('"');      

3.9控制字母大小写

String name = "Java Cookbook";
System.out.println("Normal:\t" + name);
System.out.println("Upper:\t" + name.toUpperCase());
System.out.println("Lower:\t" + name.toLowerCase());      

3.10缩排文本文档

protected int nSpaces;
Undent(int n) {
    nSpaces = n;
}
public static void main(String[] av) throws Exception {
    Undent c = new Undent(5);
    switch (av.length) {
        case 0:
            c.process(new BufferedReader(
                    new InputStreamReader(System.in)));
            break;
        default:
            for (int i = 0; i < av.length; i++)
                try {
                    c.process(new BufferedReader(new FileReader(av[i])));
                } catch (FileNotFoundException e) {
                    System.err.println(e);
                }
    }
}
public void process(BufferedReader is) throws  Exception{
        String inputLine;
        while ((inputLine = is.readLine()) != null) {
            int toRemove = 0;
            for (int i = 0; i < nSpaces && i < inputLine.length() &&
                    Character.isWhitespace(inputLine.charAt(i)); i++)
                ++toRemove;
            System.out.println(inputLine.substring(toRemove));
        }
        is.close();      

3.11输入非打印字符

System.out.println("Java Strings in action:");
    System.out.println("An alarm entered in Octal: \007");
    System.out.println("A tab key: \t(what comes after)");
    System.out.println("A newline: \n(what comes after)");
    System.out.println("A UniCode character: \u0207");
    System.out.println("A backslash character: \\");      

4.3找到匹配的文本

String patt = "Q[^u]\\d+\\.";
Pattern r = Pattern.compile(patt);
String line = "Order QT300. Now!";
Matcher m = r.matcher(line);
if (m.find()) {
    System.out.println(patt + " matches \"" +
            m.group(0) +
            "\" in \"" + line + "\"");
} else {
    System.out.println("NO MATCH");
}      

4.4替换匹配的文本

String patt = "\\bfavor\\b";
String input = "Do me a favor? Fetch my favorite.";
System.out.println("Input: " + input);
Pattern r = Pattern.compile(patt);
Matcher m = r.matcher(input);
System.out.println("ReplaceAll: " + m.replaceAll("favour"));
m.reset();
StringBuffer sb = new StringBuffer();
System.out.print("Append methods: ");
while (m.find()) {
    m.appendReplacement(sb, "favour");
}
m.appendTail(sb);
System.out.println(sb.toString());      

4.5打印匹配的所有字符串

Pattern patt = Pattern.compile("[A-Za-z][a-z]+");
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = r.readLine()) != null) {
    Matcher m = patt.matcher(line);
    while (m.find()) {
        int start = m.start(0);
        int end = m.end(0);
        System.out.println(line.substring(start, end));
    }
}
r.close();      

5.4直接使用分数而不是浮点数

double d1 = 0.666 * 5;
System.out.println(d1);
double d2 = 2/3 * 5;
System.out.println(d2);
double d3 = 2d/3d * 5;
System.out.println(d3);
double d4 = (2*5)/3d;
System.out.println(d4);
int i5 = 2*5/3;
System.out.println(i5);      

5.7舍入浮点数

public static final double THRESHOLD = 0.54;
public static int round(double d) {
    return (int)Math.floor(d + 1.0 - THRESHOLD);
}
public static void main(String[] argv) {
    for (double d = 0.1; d<=1.0; d+=0.05) {
        System.out.println("My way:  " + d + "-> " + round(d));
        System.out.println("Math way:" + d + "-> " + Math.round(d));
    }
}      

5.8格式化数字

public static final double data[] = {0, 1, 22d/7, 100.2345678};
public static void main(String[] av) {
    NumberFormat form = NumberFormat.getInstance();
    form.setMinimumIntegerDigits(3);
    form.setMinimumFractionDigits(2);
    form.setMaximumFractionDigits(4);
    for (int i=0; i<data.length; i++)
        System.out.println(data[i] + "\tformats as " +
                form.format(data[i]));
}      

5.9二进制、八进制、十进制、十六进制之间转换

String input = "101010";
for (int radix : new int[] { 2, 8, 10, 16, 36 }) {
    System.out.print(input + " in base " + radix + " is "
            + Integer.valueOf(input, radix) + "; ");
    int i = 42;
    System.out.println(i + " formatted in base " + radix + " is "
            + Integer.toString(i, radix));
}      

5.12复数的正确格式化

public static void main(String[] argv) {
    report(0);
    report(1);
    report(2);
}
public static void report(int n) {
    System.out.println("We used " + n + " item" + (n == 1 ? "" : "s"));
}      

5.18处理非常大的数字

public static Object[] testInput = {
        new BigDecimal("3419229223372036854775807.23343"),
        new BigDecimal("2.0"),
        "*",
};
public static void main(String[] args) {
    BigNumCalc calc = new BigNumCalc();
    System.out.println(calc.calculate(testInput));
}
Stack<BigDecimal> stack = new Stack<>();
public BigDecimal calculate(Object[] input) {
    BigDecimal tmp;
    for (int i = 0; i < input.length; i++) {
        Object o = input[i];
        if (o instanceof BigDecimal) {
            stack.push((BigDecimal) o);
        } else if (o instanceof String) {
            switch (((String)o).charAt(0)) {
                case '+':
                    stack.push((stack.pop()).add(stack.pop()));
                    break;
                case '*':
                    stack.push((stack.pop()).multiply(stack.pop()));
                    break;
                case '-':
                    tmp = (BigDecimal)stack.pop();
                    stack.push((stack.pop()).subtract(tmp));
                    break;
                case '/':
                    tmp = stack.pop();
                    stack.push((stack.pop()).divide(tmp,
                            BigDecimal.ROUND_HALF_UP));
                    break;
                default:
                    throw new IllegalStateException("Unknown OPERATOR popped");
            }
        } else {
            throw new IllegalArgumentException("Syntax error in input");
        }
    }
    return stack.pop();
}      

5.19TempConverter

public static void main(String[] args) {
    TempConverter t = new TempConverter();
    t.start();
    t.data();
    t.end();
}
public void data() {
    for (int i=-40; i<=120; i+=10) {
        double c = fToC(i);
        print(i, c);
    }
}
public static double cToF(double deg) {
    return ( deg * 9 / 5) + 32;
}
public static double fToC(double deg) {
    return ( deg - 32 ) * ( 5d / 9 );
}
public void print(double f, double c) {
    System.out.println(f + " " + c);
}
public void print(float f, float c) {
    System.out.printf("%6.2f %6.2f%n", f, c);
}
public void start() {
    System.out.println("Fahr    Centigrade");
}
public void end() {
    System.out.println("-------------------");
}      

5.20数字回文

public static boolean verbose = true;
public static void main(String[] argv) {
    for (int i=0; i<argv.length; i++)
        try {
            long l = Long.parseLong(argv[i]);
            if (l < 0) {
                System.err.println(argv[i] + " -> TOO SMALL");
                continue;
            }
            System.out.println(argv[i] + "->" + findPalindrome(l));
        } catch (NumberFormatException e) {
            System.err.println(argv[i] + "-> INVALID");
        } catch (IllegalStateException e) {
            System.err.println(argv[i] + "-> " + e);
        }
}
static long findPalindrome(long num) {
    if (num < 0)
        throw new IllegalStateException("negative");
    if (isPalindrome(num))
        return num;
    if (verbose)
        System.out.println("Trying " + num);
    return findPalindrome(num + reverseNumber(num));
}
protected static final int MAX_DIGITS = 19;
static long[] digits = new long[MAX_DIGITS];
static boolean isPalindrome(long num) {
    if (num >= 0 && num <= 9)
        return true;
    int nDigits = 0;
    while (num > 0) {
        digits[nDigits++] = num % 10;
        num /= 10;
    }
    for (int i=0; i<nDigits/2; i++)
        if (digits[i] != digits[nDigits - i - 1])
            return false;
    return true;
}
static long reverseNumber(long num) {
    int nDigits = 0;
    while (num > 0) {
        digits[nDigits++] = num % 10;
        num /= 10;
    }
    long ret = 0;
    for (int i=0; i<nDigits; i++) {
        ret *= 10;
        ret += digits[i];
    }
    return ret;
}      

6.1查看当天日期

LocalDate dNow = LocalDate.now();
System.out.println(dNow);
LocalTime tNow = LocalTime.now();
System.out.println(tNow);
LocalDateTime now = LocalDateTime.now();
System.out.println(now);      

6.2日期和时间的格式化

DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy/LL/dd");
System.out.println(df.format(LocalDate.now()));
System.out.println(LocalDate.parse("2014/04/01", df));
DateTimeFormatter nTZ = DateTimeFormatter.ofPattern("d MMMM, yyyy h:mm a");
System.out.println(ZonedDateTime.now().format(nTZ));      

6.3日期/时间、YMDHMS和纪元秒之间的转换

Instant epochSec = Instant.ofEpochSecond(1000000000L);
ZoneId zId = ZoneId.systemDefault();
ZonedDateTime then = ZonedDateTime.ofInstant(epochSec, zId);
System.out.println("The epoch was a billion seconds old on " + then);
long epochSecond = ZonedDateTime.now().toInstant().getEpochSecond();
System.out.println("Current epoch seconds = " + epochSecond);
LocalDateTime now = LocalDateTime.now();
ZonedDateTime there = now.atZone(ZoneId.of("Canada/Pacific"));
System.out.printf("When it's %s here, it's %s in Vancouver%n",now, there);      

6.4将字符串解析为日期

String armisticeDate = "1914-11-11";
LocalDate aLD = LocalDate.parse(armisticeDate);
System.out.println("Date: " + aLD);
String armisticeDateTime = "1914-11-11T11:11";
LocalDateTime aLDT = LocalDateTime.parse(armisticeDateTime);
System.out.println("Date/Time: " + aLDT);
//这里好像有点问题
DateTimeFormatter df = DateTimeFormatter.ofPattern("dd MMM uuuu");
String anotherDate = "27 Jan 2012";
LocalDate random = LocalDate.parse(anotherDate, df);
System.out.println(anotherDate + " parses as " + random);
System.out.println(aLD + " formats as " + df.format(aLD));      

6.5两个日期之间的差

LocalDate endofCentury = LocalDate.of(2000, 12, 31);
LocalDate now = LocalDate.now();
Period diff = Period.between(endofCentury, now);
System.out.printf("The 21st century (up to %s) is %s old%n", now, diff);
System.out.printf("The 21st century is %d years, %d months and %d days old",
        diff.getYears(), diff.getMonths(), diff.getDays());      

6.6日期或日历的加减

LocalDate now = LocalDate.now();
Period p = Period.ofDays(700);
LocalDate then = now.plus(p);
System.out.printf("Seven hundred days from %s is %s%n", now, then);      

6.7与传统日期和日历类的接口

Date legacyDate = new Date();
System.out.println(legacyDate);
LocalDateTime newDate = LocalDateTime.ofInstant(legacyDate.toInstant(), ZoneId.systemDefault());
System.out.println(newDate);
Calendar c = Calendar.getInstance();
System.out.println(c);
LocalDateTime newCal = LocalDateTime.ofInstant(c.toInstant(),ZoneId.systemDefault());
System.out.println(newCal);      

参考文献

《Java经典实例》  lan F.Darwin著  李新叶 余晓晔译

转载于:https://my.oschina.net/MoreYoungGavin/blog/906930