Java之输入和输出

时间:2019-11-08
本文章向大家介绍Java之输入和输出,主要包括Java之输入和输出使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

  输出

  在前面的代码中,我们总是用System.out.println()来向屏幕输出一些内容:

  println是print line的缩写,表示输出并换行。因此,如果输出后不想换行,可以用print()

public class Main {
    public static void main(String[] args) {
        System.out.print("A,");
        System.out.print("B,");
        System.out.print("C.");
        System.out.println();
        System.out.println("END");
    }
}

   输出

A,B,C.
END

   格式化输出

  Java还提供了格式化输出的功能。为什么要格式化输出?因为计算机表示的数据不一定适合人来阅读:

public class Main {
    public static void main(String[] args) {
        double d = 12900000;
        System.out.println(d); // 1.29E7
    }
}

   输出

1.29E7

   如果要把数据显示成我们期望的格式,就需要使用格式化输出的功能。格式化输出使用System.out.printf(),通过使用占位符%?,printf()可以把后面的参数格式化成指定格式:

public class Main {
    public static void main(String[] args) {
        double d = 3.1415926;
        System.out.printf("%.2f\n", d); // 显示两位小数3.14
        System.out.printf("%.4f\n", d); // 显示4位小数3.1416
    }
}

   输出

3.14
3.1416

   如果运行报错

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
	The method printf(String, Object[]) in the type PrintStream is not applicable for the arguments (String, double)
	The method printf(String, Object[]) in the type PrintStream is not applicable for the arguments (String, double)

	at Main.main(Main.java:4)

   Eclipse中 JAVA默认的兼容版本为1.4, 改为1.5及以上版本就行。 项目 》属性》Java complier》complier compliance lever:1.5

   Java的格式化功能提供了多种占位符,可以把各种数据类型格式化成指定字符串:

  

占位符说明
%d 格式化输出整数
%x 格式化输出十六进制整数
%f 格式化输出浮点数
%e 格式化输出科学计数法表示的浮点数
%s 格式化字符串

  

  

原文地址:https://www.cnblogs.com/minseo/p/11821103.html