• Java练习:tips.Print


    在学习Java时和《编程导论(Java)》中,大量使用了重载的System.out.println()等类似的输出语句。特别是书籍中,一行语句中包括System.out.println会显得太长,超过一行代码40个字符的限制,因而请静态引入tips.Print并使用相应方法代替它们。通常以

    • p替代System.out.print。
    • pln替代System.out.println

    《编程导论(Java)》代码库中有tips.Print,学习设计模式时使用的是tool.Print。

    package tips;
    import java.io.PrintStream;
    /**
     * 到处都是System.out.println().假设一个例程中使用它们较多,请使用本类。
     * 1.2.1类体结构,练习要求阅读本类。

    * @see java.io.PrintStream * @author yqj2065 * @version 0.1 */ public class Print{ public static void pln(Object x){ System.out.println(x); } public static void pln(){ System.out.println(); } public static void p(Object x){ System.out.print(x); } /** * 使用指定格式字符串和參数,打印格式化的字符串。

    */ public static PrintStream pf(String format, Object... args){ return System.out.printf(format,args); } public static void pfln(String format, Object... args){ System.out.printf(format,args). println(); } }

    对于大量的System.out.println。能够用 pln取代。微笑

    改动:

    1.pln(char[] arr)

    System.out.println有大量的重载方法,而tips.Print的pln仅仅有两个重载方法。

    对于char[], pln(char[])与System.out.println(char[])就不一致了。

    今天看一个贴子。上面有Java Puzzlers的第12个谜题,于是发现了这个问题。

        public static void bug() {        
            System.out.println(new char[]{'1', '2', '3'});
            pln(new char[]{'1', '2', '3'});
            pln(null);
        }

    输出为:

    123
    [C@78c45512

    查看JDK源码:

        public void println(Object x) {  
            String s = String.valueOf(x);  
            synchronized (this) {  
                print(s);  
                newLine();  
            }  
        }

    tips.Print中没有重载System.out.println(char[])!因而char[]自己主动造型为Object。输出为引用的“大概模样”。

    而System.out.println(char[])。其文档说明:

     print(char[] s)  Prints an array of characters. The characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

    所以输出打印:123


    这个bug也有一个优点:

            char[] cs = null;
            pln(cs);
            System.out.println(cs); 

    pln(Object)不怕null。pln(cs)打印null。而System.out.print(cs) 会抛出NullPointerException(java.io.Writer.write())

    2.pln(int[] arr)

    为了打印int[],加入

        public static void pln(int[] arr){
            System.out.print(java.util.Arrays.toString(arr));
        }


     Java编程练习文件夹


  • 相关阅读:
    Asp.net 默认配置下,Session莫名丢失的原因及解决办法
    回发或回调参数无效。在配置中使用 enableEventValidation=true或在页面中使用 启用了事件验证。
    SQL Server事务日志意外增大的处理方法
    SQLServer数据库设计表和字段(转)
    关于SQL Server数据库设计的感悟
    如何动手组建WiFi网络
    教你在SQL Server数据库中设计表和字段
    SQL Server数据库设计表和字段的经验
    SQL Server 的通用分页显示存储过程
    翻译: jQuery1.4官方文档
  • 原文地址:https://www.cnblogs.com/zhchoutai/p/6769255.html
Copyright © 2020-2023  润新知