预备知识
Scanner:
Scanner input = new Scanner(System.in);
- nextInt():输入整数,只读取整数类型数据, nextInt()在读取完输入后把光标放在读取数据的同一行,该数据的后面。当我们一直使用其读数据的时候,此时遇到回车的时候会自动换行,继续读数据。
- nextDouble():输入双精度数
- next():输入字符串(以空格作为分隔符)。只读取到空格,不能读取被空格分开的两个单词(也就是不能读取空格),并且在读取完后把光标放在读取数据的同一行,该数据的后面。以空格、回车、Tab键都会视为结束符。
- nextLine():输入字符串(以回车最为分隔符)。读取整行的数据包括单词间的空格,到回车结束(也就是从开始读一整行包括回车),读取结束后,光标放在下一行开头。
String:
- trim() //去掉头尾的空格
- replace(" “,”") //中间有空格,替换所有空格
- str.replaceAll("\\s+"," “).split(” ");//把连续空格替换成一个空格再切割
示例
import java.util.Scanner;
public class TestScanner {
/**
1.两数求和 一直输入
1 5
10 20
6
30
*/
static void test1(){
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
int a = scanner.nextInt();
int b = scanner.nextInt();
System.out.println(a+b);
}
}
/**
2.两数求和 有组数
2(组数)
1 5
10 20
6
30
*/
static void test2(){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
while (n-->0){
int a = scanner.nextInt();
int b = scanner.nextInt();
System.out.println(a+b);
}
}
/** 3. 数组求和 有组数
2(组数)
4 1 2 3 4 (4个数 和为1+2+3+4 )
5 1 2 3 4 5
10
15
*/
static void test3(){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
while (n-->0){
int len = scanner.nextInt();
int sum = 0;
while(len-->0){
sum += scanner.nextInt();
}
System.out.println(sum);
}
}
/** 4. 数组求和 直接求 一直输入
1 2 3
4 5
0 0 0 0 0
6
9
0
*/
static void test4(){
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
int sum = 0;
String[] strings = scanner.nextLine().split(" ");
for(String s:strings){
sum += Integer.valueOf(s);
}
System.out.println(sum);
}
}
/** 5. 字符串 一直输入
a c bb
f dddd
nowcoder
acbb
fdddd
nowcoder
*/
static void test5(){
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
String[] strings = scanner.nextLine().split(" ");
String res = "";
for(String s:strings){
res += s;
}
System.out.println(res.trim());//去除回车
System.out.println(res.length());
}
}
static void test6(){
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
String[] strings = scanner.nextLine().split(",");
String res = "";
for(String s:strings){
// res += s.trim();//去掉头尾的空格
res += s.replace(" ","");//中间有空格,替换所有空格
}
System.out.println(res);
System.out.println(res.length());
}
}
public static void main(String[] args){
// test1();
// test2();
// test3();
// test4();
// test5();
// test6();
}
}
易错点
- nextInt()或者next()读取完毕并回车之后其后紧跟nextLine(),就会导致nextLine()读取到空值,因为nextLine()自动读取到’\n’,意味着遇到结束符;
- 有时候将字符串转为整数时,代码没问题却提示数组越界,往往是因为字符串代表的整数超过了int的最值,需要改用long。