廖雪峰Java1-3流程控制-1输入输出
1.输入
- 导入java.util.Scanner
- 创建Scanner对象并传入System.in
- 使用Scanner.nextLine()读取用户输入的字符串
- Scanner.nextInt()读取用户输入的整数
import java.util.Scanner;
public class Hello {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Input your name:");
String name = scanner.nextLine();
System.out.println("Input your age:");
int age = scanner.nextInt();
System.out.println("hi, "+ name + ", you are "+age);
}
}
![](https://img2018.cnblogs.com/blog/1418970/201901/1418970-20190110192549978-1667228525.png)
2.输出
System.out.println("输出换行");
System.out.print("输出但不换行");
格式化输出
用作短信模版,或控制字符格式使数据更易读。
- System.out.printf()
- 使用占位符%xxx
- 常用的占位符
|%d 整数|%x 十六进制整数|%f 浮点数|%% %字符本身|
|--------|---------------|---------|-------------|
double d = 3.1415926;
System.out.println(d);
System.out.printf("PI = %.2f\n", d);//保留2位小数点
System.out.printf("PI = %7.2f\n", d);//一共7位
System.out.printf("%s is %d years old\n","Bob",12);
double f = 0.123456;
System.out.printf("%f\n", f);
System.out.printf("%e\n", f);//科学计数法表示小数
System.out.printf("%.2f\n", f);
System.out.printf("%6.2f\n", f);
System.out.printf("%+.2f\n", f);//打印符号位
//调整参数顺序
System.out.printf("%s %s %s \n", "A", "B", "C");
System.out.printf("%2$s %1$s %1$s %3$s\n", "A", "B", "C");//1$s表示第一个参数
//System.out.printf("%s %s","hello");//参数可以多,但不能少。少了会报异常java.util.MissingFormatArgumentException
![](https://img2018.cnblogs.com/blog/1418970/201901/1418970-20190110195821879-529632443.png)
搜索Format String Syntax,即可找到更多参数说明。https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html
总结
- 输出换行println()/不换行print()/格式化输出printf()
- 输入nextLine()\nextInt()\nextDouble()...