跳到主要内容
版本:1.0

控制台输入输出

控制台交互是入门阶段最常用的输入输出方式。

输出​

System.out.println("换行输出");
System.out.print("不换行输出");
System.out.printf("%s 今年 %d 岁,身高 %.2f 米%n", "Alice", 18, 1.65);

printf 常用占位符:

占位符类型
%d整数
%f / %.2f浮点数(保留两位小数)
%s字符串
%n换行

Scanner 输入​

java.util.Scanner 是读取控制台输入的常用类:

import java.util.Scanner;

Scanner sc = new Scanner(System.in);

System.out.print("请输入姓名:");
String name = sc.nextLine(); // 读取一整行(含空格)

System.out.print("请输入年龄:");
int age = sc.nextInt(); // 读取整数

System.out.print("请输入身高:");
double height = sc.nextDouble();

System.out.printf("%s,%d 岁,%.2f 米%n", name, age, height);

常用读取方法​

方法说明
next()读取一个"单词"(遇空格停止)
nextLine()读取一整行
nextInt() / nextDouble()读取数值
hasNext() / hasNextInt()先判断再读取,避免类型不匹配异常

nextLine 的坑​

nextInt() 之后紧跟 nextLine() 会读到残留的回车符,导致读到一个空串:

int age = sc.nextInt();
sc.nextLine(); // 先吃掉残留换行
String name = sc.nextLine();

循环读取直到结束​

Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int n = sc.nextInt();
System.out.println("读到:" + n);
}
// 输入非整数内容时结束循环