1.Scanner类
基本用法(示例):
import java.util.Scanner; //需要导入java.util.Scanner包
Scanner s = new Scanner(System.in);
(1)输入字符串,以回车或空格作为字符串的结束,不接收带空格的字符串
String str = s.next();
(2)输入字符串,以回车作为字符串的结束,可接受空格作为字符串的一部分
String str= s.nextLine();
(3)输入整数
int n= s.nextInt();
(4)输入浮点数
double d= s.nextDouble();
(5)输入布尔类型数据
boolean i = s.nextBoolean();
(6)输入字符
Scanner类没有提供直接输入char类型的方法,可以通过charAt()方法从next()或nextLine()获取输入的字符。
String str = s.next();
char c = str.charAt(0);
从字符串str中获取第一个字符,下标从0开始
2.System.in.read()和System.out.write()
基本用法(示例):
import java.io.*;
int i;
i= System.in.read();
System.out.write(i);
之前用System.out.println(i);输出i,当我输入i=7时,输出的i为55。原因在于System.in.read()返回的是输入数值的 ASKII 码,所以要用System.out.write()将其转换回来
3.BufferedReader的用法
基本用法(示例):
import java.io.*;
BufferedReader buf=
new BufferedReader(new InputStreamReader(System.in));
int a = Integer.parseInt(buf.readLine()); //输入整数
double b = Double.parseDouble(buf.readLine()); //输入浮点数
String str = buf.readLine(); //输入字符串
char c = (char)buf.read(); //输入字符
4.输出
system.out.println() //自动换行输出
system.out.print() //不换行输出
system.out.printf() //类似C语言的格式输出
例如:
String s = “Hello“;
System.out.printf(“%s”, s);