java的普通输出和快速输出
一、普通输出(普遍使用,但是速度一般)
我们最开始接触的输出方法,使用最为普遍的方法
1、使用步骤
System.out.println("hello world")
2、常用方法
// 常规输出带换行
System.out.println("Hello World!");
// 常规输出不换行
System.out.print("Hello World!");
// 格式化输出
System.out.printf("Hello %s!", "world");
3、使用示例
public class TestOutput {
public static void main(String[] args) {
System.out.println("输出带换行");
System.out.print("输出不带换行");
System.out.println(); // 换行作用
System.out.printf("格式化输出:%s \n", "hello");
System.out.printf("%.2f", 3.14159);
}
}
二、快速输出(比普通输出快,但是有小陷阱)
经常在竞赛中使用
1、使用步骤
-
创建类变量
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
-
调用方法
out.write("hello world"); out.flush();
2、常用方法
- write()
- flush()
注意:
如果想要直接输出数字,需要把数字变成字符串,因为如果用write方法直接输出,输出的是乱码
每次输出完以后需要调用flush进行缓存刷新,否则控制台不显示
3、使用示例
public class TestOutput {
public static void main(String[] args) throws IOException {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
out.write("hello world");
out.write(""+20);
out.flush();
}
}