文档章节

Java经典实例

MoreYoungG
 MoreYoungG
发布于 2017/05/22 20:56
字数 1619
阅读 14
收藏 0

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著  李新叶 余晓晔译

© 著作权归作者所有

共有 人打赏支持
MoreYoungG
粉丝 19
博文 25
码字总数 440766
作品 0
广州
Java程序员必读书单,家族又添新成员

点击关注异步图书,置顶公众号 每天与你分享IT好书 技术干货 职场知识 参与文末话题讨论,每日赠送异步图书。 ——异步小编 有些革命出其不意地吸引了全世界的眼球。Twitter、Linux操作系统和...

异步社区
05/09
0
0
通过 HttpAuthenticationMechanism 执行 Web 身份验证

通过 Java EE 8 中新的注解驱动的 HTTP 身份验证机制执行经典和自定义的 Servlet 身份验证 系列内容: 此内容是该系列 4 部分中的第 # 部分: Java EE 8 Security API 入门,第 2 部分 http...

Alex Theedom
04/02
0
0
Java GC系列:Java垃圾回收详解

Java的内存分配与回收全部由JVM垃圾回收进程自动完成。与C语言不同,Java开发者不需要自己编写代码实现垃圾回收。这是Java深受大家欢迎的众多特性之一,能够帮助程序员更好地编写Java程序。 ...

满风
2015/04/10
0
0
14、Java并发性和多线程-Java ThreadLocal

以下内容转自http://ifeve.com/java-theadlocal/: Java中的ThreadLocal类可以让你创建的变量只被同一个线程进行读和写操作。因此,尽管有两个线程同时执行一段相同的代码,而且这段代码又有...

easonjim
2017/06/16
0
0
《Java性能优化指南》读书笔记-JVM性能调优具体方法

选择jvm部署模式 应用在部署的时候,是单个jvm实例,还是选择多个实例?该如何选择? 单个jvm实例存在的问题是单点故障。当我们jvm实例出现故障的时候或者我们需要重启或者部署的时候都会影响...

杨武兵
2015/08/03
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

php 使用redis锁限制并发访问类

1.并发访问限制问题 对于一些需要限制同一个用户并发访问的场景,如果用户并发请求多次,而服务器处理没有加锁限制,用户则可以多次请求成功。 例如换领优惠券,如果用户同一时间并发提交换领...

豆花饭烧土豆
22分钟前
0
0
Linux环境搭建 | 手把手教你配置Linux虚拟机

在上一节 「手把你教你安装Linux虚拟机」 里,我们已经安装好了Linux虚拟机,在这一节里,我们将配置安装好的Linux虚拟机,使其达到可以开发的程度。 Ubuntu刚安装完毕之后,还无法进行开发,...

良许Linux
24分钟前
0
0
Nginix开启SSL支持HTTPS访问(自签名方法)

Nginix开启SSL支持HTTPS访问(自签名方法) 超文本传输安全协议(缩写:HTTPS,英语:Hypertext Transfer Protocol Secure)是超文本传输协议和SSL/TLS的组合,用以提供加密通讯及对网络服务器...

openthings
40分钟前
0
0
(三)Nginx配置·续

概述 前文写了关于Nginx环境配置,但是还没有完,接下来将会继续讲三个相关的配置 主要是以下三个 1.Nginx访问日志 2.Nginx日志切割 3.静态文件不记录日志和过期时间 Nginx访问日志 1.先看看...

杉下
今天
1
0
jquery创建类似于java的map

var map = {}; // Map map = new HashMap(); map[key] = value; // map.put(key, value); var value = map[key]; // Object value = map.get(key); var has = key in map; // boolean has = ......

SuperDabai
今天
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部