一.Scanner读取控制台
1.Scanner.next():读取一个字符串截止到空格或者回车,返回字符串类型
Scanner sc = new Scanner(System.in);
String s = sc.next();
String s1 = sc.next();
System.out.println(s);
System.out.println(s1);
输入:
abc cdb
输出:
abc
cbd
输入:
abc
cbd
输出:
abc
cbd
2.Scanner.nextInt():读取一个整数截止到空格或回车,返回Int类型
int num1 = sc.nextInt();
int num2 = sc.nextInt();
System.out.println(num1);
System.out.println(num2);
输入:
123 321
输出:
123
321
输入:
123
321
123
321
3.Scanner.nextline():读取一行,截止到回车,返回字符串类型
String s = sc.nextLine();
String s1 = sc.nextLine();
System.out.println(s);
System.out.println(s1);
输入:
abcd efg
123 456
输出:
abcd efg
123 456
这里说明一下除去nextline(),其余方法读取时会跳过有效字符前的空白,直至读取到有效字符
其余函数 nextLong,nextFloat,nextDouble与next和nextInt比较类似,这里就不做介绍了。
二.更快的读取信息
众所周知 (个锤子),Scanner读取信息时十分缓慢的,会严重影响程序效率,至于为什么会这么慢,我找了一晚上资料就找到这么一篇文章,能力有限只能读个大概,就不解释了,免得丢人现眼,有大佬了解可以在评论区分享一下。
至于如何解决这个问题,我这边贴一份代码,大佬的代码原文,我这边简单写了一下注释。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class main{
static InputReader in;
static PrintWriter out;
public static void main(String[] args) throws IOException {
}
static class InputReader {
BufferedReader br;
//构造函数
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
//获取下一个int类型整数
public int nextInt() throws IOException {
//读取下一个字符的ascii,返回
int c = br.read();
//当读取到的字符为空,不断循环读取
while (c <= 32) {
c = br.read();
}
//negative用于判定正负
boolean negative = false;
//当读取到的第一个字符为‘-’号,negative为true,读取下一个字符
if (c == '-') {
negative = true;
c = br.read();
}
//声明一个x变量
int x = 0;
//当读取到的字符不为空,则继续循环
while (c > 32) {
//c减去0的ascii码的差值就是c对应的值
x = x * 10 + c - '0';
//读取下一个字符
c = br.read();
}
//三元运算符,当negative为负返回负数,否则返回正数
return negative ? -x : x;
}
//获取下一个long类型整数
public long nextLong() throws IOException {
int c = br.read();
while (c <= 32) {
c = br.read();
}
boolean negative = false;
if (c == '-') {
negative = true;
c = br.read();
}
long x = 0;
while (c > 32) {
x = x * 10 + c - '0';
c = br.read();
}
return negative ? -x : x;
}
//获取下一个字符串
public String next() throws IOException {
int c = br.read();
while (c <= 32) {
c = br.read();
}
StringBuilder sb = new StringBuilder();
while (c > 32) {
sb.append((char) c);
c = br.read();
}
return sb.toString();
}
//获取下一个浮点数
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}