zoukankan      html  css  js  c++  java
  • java之格式化输出

    参考http://how2j.cn/k/number-string/number-string-foramt/320.html#nowhere

    格式化输出

    如果不使用格式化输出,就需要进行字符串连接,如果变量比较多,拼接就会显得繁琐
    使用格式化输出,就可以简洁明了

    %s 表示字符串
    %d 表示数字
    %n 表示换行

    使用System.out.printf

    package digit;
      
    public class TestNumber {
      
        public static void main(String[] args) {
     
            String name ="盖伦";
            int kill = 8;
            String title="超神";
             
            //直接使用+进行字符串连接,编码感觉会比较繁琐,并且维护性差,易读性差
            String sentence = name+ " 在进行了连续 " + kill + " 次击杀后,获得了 " + title +" 的称号";
             
            System.out.println(sentence);
             
            //使用格式化输出
            //%s表示字符串,%d表示数字,%n表示换行
            String sentenceFormat ="%s 在进行了连续 %d 次击杀后,获得了 %s 的称号%n";
            System.out.printf(sentenceFormat,name,kill,title);
             
        }
    }

    printf和format

    printf的源码

    package digit;
      
    public class TestNumber {
      
        public static void main(String[] args) {
     
            String name ="盖伦";
            int kill = 8;
            String title="超神";
             
            String sentenceFormat ="%s 在进行了连续 %d 次击杀后,获得了 %s 的称号%n";
            //使用printf格式化输出
            System.out.printf(sentenceFormat,name,kill,title);
            //使用format格式化输出
            System.out.format(sentenceFormat,name,kill,title);
             
        }
    }

    换行符

    换行符就是另起一行 --- ' ' 换行(newline)
    回车符就是回到一行的开头 --- ' ' 回车(return)
    在eclipse里敲一个回车,实际上是回车换行符
    Java是跨平台的编程语言,同样的代码,可以在不同的平台使用,比如Windows,Linux,Mac
    然而在不同的操作系统,换行符是不一样的
    (1)在DOS和Windows中,每行结尾是 “ ”;
    (2)Linux系统里,每行结尾只有 “ ”;
    (3)Mac系统里,每行结尾是只有 " "。
    为了使得同一个java程序的换行符在所有的操作系统中都有一样的表现,使用%n,就可以做到平台无关的换行

    package digit;
      
    public class TestNumber {
      
        public static void main(String[] args) {
     
            System.out.printf("这是换行符%n");
            System.out.printf("这是换行符%n");
             
        }
    }
  • 相关阅读:
    进程与线程
    the art of seo(chapter seven)
    the art of seo(chapter six)
    the art of seo(chapter five)
    the art of seo(chapter four)
    the art of seo(chapter three)
    the art of seo(chapter two)
    the art of seo(chapter one)
    Sentinel Cluster流程分析
    Sentinel Core流程分析
  • 原文地址:https://www.cnblogs.com/lijingran/p/9128174.html
Copyright © 2011-2022 走看看