一、输出到控制台
(一)、基本语法
System.out.println(msg); // 输出一个字符串, 带换行
System.out.print(msg); // 输出一个字符串, 不带换行
System.out.printf(format, msg); // 格式化输出
1、println 输出的内容自带 \n, print不带 \n
2、printf 的格式化输出方式和 C 语言的 printf 是基本一致的.
(二)、代码示例
System.out.println("hello world");
int x = 10;
Systrm.out.printf("x = %d\n", x)
(三)、格式化字符串
转换符 | 类型 | 举例 | |
d | 十进制整数 | ("%d", 100) | 100 |
x | 十六进制整数 | ("%x", 100) | 64 |
o | 八进制整数 | ("%o", 100) | 144 |
f | 定点浮点数 | ("%f", 100f) | 100.000000 |
e | 指数浮点数 | ("%e", 100f) | 100.0001.000000e+02 |
g | 通用浮点数 | ("%g", 100f) | 100.000 |
a | 十六进制浮点数 | ("%a", 100) | 0x1.9p6 |
s | 字符串 | ("%s", 100) | 100 |
c | 字符 | ("%c", ‘1’) | 1 |
b | 布尔值 | ("%b", 100) | ture |
h | 散列码 | ("%h", 100) | 64 |
% | 百分号 | ("%.2f%%", 2/7f) | 0.29% |
二、从键盘输入
1、使用 Scanner 读取字符串/整数/浮点数
import java.util.Scanner; // 需要导入 util 包
Scanner sc = new Scanner(System.in);
System.out.println("请输入你的姓名:");
String name = sc.nextLine();
System.out.println("请输入你的年龄:");
int age = sc.nextInt();
System.out.println("请输入你的工资:");
float salary = sc.nextFloat();
System.out.println("你的信息如下:");
System.out.println("姓名: "+name+"\n"+"年龄:"+age+"\n"+"工资:"+salary);
sc.close(); // 注意, 要记得调用关闭方法
// 执行结果
请输入你的姓名:
张三
请输入你的年龄:
18
请输入你的工资:
1000
你的信息如下:
姓名: 张三
年龄:18
工资:1000.0
2、输入数据类型的方法
Method | Example |
nextByte() | byte b=scanner.nextByte() |
nextDouble() | double d=scanner.nextDouble() |
nextFloat() | float f=scanner.nextFloat() |
nextInt() | int i=scanner.nextInt() |
nextLong() | long l=scanner.nextLong() |
nextShort() | short s=scanner.nextShort() |
next | String s=scanner.next |
3、注意事项:
(1)、当循环输入多个数据的时候, 使用 ctrl + z 或者(ctrl+ d)来结束输入 ,(Linux / Mac 上使用 ctrl+ d).
(2)、读入一个单词,使用next方法
sc.next():接收字符串,但是在接收时,遇到空格之后就终止接收了,即:空格之后的内容不会接收的,
(3)、读入一行字符串,使用nextLine方法
sc.nextLine():用来接收字符串,将整行的字符串全部接收了