Two commonly used output methods in java: print() and println(). There is no obvious difference in the input conditions when using these two output methods. The difference is reflected in whether there is a newline at the end of the output. [Recommended learning: java course]
eg:
public class eg { //交叉使用可以体会到作用的差异 public static void main(String[] args) { System.out.print("123456"); System.out.println("abced"); System.out.println("abced"); System.out.print("123456"); System.out.println("abced"); } }
Result:
Analysis result: not ugly Out, every time print() is used, the next output (abced) is followed at the end, that is: print() does not wrap. And every time there is a line break after abced.
Note: When using print(), no content output is required
eg:
public class eg { public static void main(String[] args) { System.out.print();//此时print无内容输出 } }
public class add { //由于使用单独的一行无法体现结果,所以加入print()显示效果 public static void main(String[] args) { System.out.print("123456"); System.out.print("123456"); System.out.println(); System.out.print("123456"); } }
public class eg { //与上图的代码进行对比 效果显而易见 public static void main(String[] args) { System.out.print("123456"); System.out.print("123456"); System.out.print("\n"); System.out.print("123456"); } }
In addition to the above two common outputs, java also has a powerful output: printf()
Note:package com.hone.test; // "%"表示进行格式化输出, "%"之后的内容为格式的定义。 public class Printf { public static void main(String[] args) { double d = 345.678; String s = "hello World"; int a = 123; //浮点型的输出 System.out.printf("%,d",a); //格式化输出数据,每三个数据加上一个, System.out.println(); System.out.printf("%f", d); // 345.678000 System.out.println(); //"9.2"中的9表示输出的长度,2表示小数点后的位数。 345.678位数不够前面不上空格 System.out.printf("%9.3f", d); System.out.println(); System.out.printf("%+9.3f", d); //"+"表示输出的数带正负号 System.out.println(); System.out.printf("%-9.3f", d); //"-"表示输出的数左对齐(默认为右对齐) System.out.println(); System.out.printf("%+-9.3f",d); //"+-"表示输出的数带正负号且左对齐 System.out.println(); //整型的输出 System.out.printf("%d", a); //"d"表示输出十进制整数。 System.out.println(); System.out.printf("%04d", a); //规定为4位,不够左边添加0 System.out.println(); System.out.printf("%d%%", a); //如果想输出百分数,则连续用两个 %% System.out.println(); System.out.printf("%o", a); //"o"表示输出八进制整数。 System.out.println(); System.out.printf("%x", a); //"x"表示输出八进制整数。 //字符串的输出 System.out.println(); System.out.printf("%s%n", s); //输出字符串,其中 %n表示换行 System.out.printf("输出一个浮点数:%.3f,一个整数:%d,一个字符串:%s",d,a,s); //输出多个变量 } }
The above is the detailed content of How to output in java?. For more information, please follow other related articles on the PHP Chinese website!