文档章节

Java经典实例

MoreYoungG
 MoreYoungG
发布于 2017/05/22 20:56
字数 1619
阅读 12
收藏 0
点赞 0
评论 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

通过 HttpAuthenticationMechanism 执行 Web 身份验证

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

Alex Theedom ⋅ 04/02 ⋅ 0

14、Java并发性和多线程-Java ThreadLocal

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

easonjim ⋅ 2017/06/16 ⋅ 0

培训云计算学校,虚拟机基本结构讲解

我们要对JVM虚拟机的结构有一个感性的认知。毕竟我们不是编程人员,认知程度达不到那么深入。一个运行时的Java虚拟机实例的天职是:负责运行一个java程序。当启动一个Java程序时,一个虚拟机...

长沙千锋 ⋅ 05/17 ⋅ 0

android -------- java虚拟机和Dalvik虚拟机

java虚拟机 虚拟机是一种抽象化的计算机,通过在实际的计算机上仿真模拟各种计算机功能来实现的。Java虚拟机有自己完善的硬体架构,如处理器、堆栈、寄存器等,还具有相应的指令系统。Java虚...

切切歆语 ⋅ 04/29 ⋅ 0

ThreadLocal源码分析

阅读原文请访问我的博客 BrightLoong's Blog 一. 简介 提醒篇幅较大需耐心。 简介来自ThreadLocal类注释 ThreadLocal类提供了线程局部 (thread-local) 变量。这些变量与普通变量不同,每个线...

BrightLoong ⋅ 05/28 ⋅ 0

阿里年薪50WJAVA工程师转大数据学习路线!

大数据有两个方向,一个是偏计算机的,另一个是偏经济的。你学过Java,所以你可以偏将计算机的。 Java程序员想转大数据可行吗?Java是全世界使用人数最多的编程语言。不少程序员选择Java做为...

JAVA丶学习 ⋅ 04/25 ⋅ 0

12、Java并发性和多线程-Java同步块

以下内容转自http://ifeve.com/synchronized-blocks/: Java 同步块(synchronized block)用来标记方法或者代码块是同步的。Java同步块用来避免竞争。本文介绍以下内容: Java同步关键字(s...

easonjim ⋅ 2017/06/15 ⋅ 0

使用JDBC操作SAP云平台上的HANA数据库

本文假设您对JDBC(Java Database Connectivity)有最基本的了解。您也可以将其同ADBC(ABAP Database Connectivity)做对比,细节请参考我的博客ADBC and JDBC 这篇文章分为两部分,第一部分内容...

JerryWang_SAP ⋅ 05/19 ⋅ 0

IntelliJ IDEA 2018.1.3 + jdk1.8 安装教程

1.写在前面 由于同学的项目缺人手,欲拉我参与其中,该项目由java编写,所以开始了我的java学习。当然首先是安装java环境啦。 2.安装IDEA 由于这个是收费的,我等穷逼哪搞得起。只能破解使用...

我只是一只小小鸟 ⋅ 05/21 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

ARMS: 原来实时计算可以这么简单!

摘要: 业务实时监控服务( ARMS)是一款阿里云应用性能管理(APM)类监控产品。借助本产品,您可以基于前端、应用、业务自定义等服务,迅速便捷地为企业构建秒级响应的业务监控能力。 业务实...

阿里云云栖社区 ⋅ 3分钟前 ⋅ 0

Monkey入门_琉璃

先下载android sdk安装配置好路径,然后adb shell 如果给你显示这个,说明目前没有有效的移动设备链接,可以开个安卓模拟器或者使用真机,usb或wifi链接到电脑都可以,打开usb调试模式;然后...

EvanDev ⋅ 5分钟前 ⋅ 0

Idea类注释模板

一、设置类注释模板 1.选择File–>Settings–>Editor–>File and Code Templates–>Includes–>File Header. 2.设置完成后,创建类时自动生成注释,效果如下。...

Clarence_D ⋅ 6分钟前 ⋅ 0

vuejs题

1、active-class是哪个组件的属性?嵌套路由怎么定义? 答:vue-router模块的router-link组件。 2、怎么定义vue-router的动态路由?怎么获取传过来的动态参数? 答:在router目录下的index.j...

自由小鸟 ⋅ 6分钟前 ⋅ 0

2018年社交系统ThinkSNS年中大促

致各大商企事业单位及粉丝用户: 为感谢大家对ThinkSNS品牌的关注与支持,2018年6月18日官方诚推出:年中大促,限时抢购活动! “ThinkSNS 年中大促,¥6.18超值特惠 名额有限,预购从速! ...

ThinkSNS账号 ⋅ 12分钟前 ⋅ 0

MYSQL主从复制搭建及切换操作(GTID与传统)

如下: MYSQL主从复制方式有默认的复制方式异步复制,5.5版本之后半同步复制,5.6版本之后新增GTID复制,包括5.7版本的多源复制。 MYSQL版本:5.7.20 操作系统版本:linux 6.7 64bit 1、异步...

rootliu ⋅ 13分钟前 ⋅ 0

Java强软弱虚引用Reference

Java强软弱虚引用Reference 本文目的:深入理解Reference 本文定位:学习笔记 学习过程记录,加深理解,提升文字组合表达能力。也希望能给学习Reference的同学一些灵感 源码说明 源码基于jdk...

lichuangnk ⋅ 15分钟前 ⋅ 0

plsql 表中字段及注释时为乱码

在windows中创 建一个名为“NLS_LANG”的系统环境变量,设置其值为“SIMPLIFIED CHINESE_CHINA.ZHS16GBK”, 然后重新启动 pl/sql developer,这样检索出来的中文内容就不会是乱码了。如...

江戸川 ⋅ 18分钟前 ⋅ 0

Docker创建JIRA 7.2.7中文破解版

1、介绍 1.1、什么是JIRA?   关于JIRA网上的介绍有很多,以下摘自百度百科:   JIRA是Atlassian公司出品的项目与事务跟踪工具,被广泛应用于缺陷跟踪、客户服务、需求收集、流程审批、任...

谢思华 ⋅ 22分钟前 ⋅ 0

Java Class 类使用

Java Class 类使用 我们可以通过已知的包名来获取到 Class 对象,从而可以通过反射动态的来操作对象。 获取Class有三种方式 //通过对象.class直接获取Class integerClass = Integer.class;...

gaob2001 ⋅ 27分钟前 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部