Java Scanner
- 一、next()
- 二、nextLine()
- 三、应用
一、next()
- 用于从标准输入读取下一个字符串。该方法会扫描输入流并返回下一个非空白字符序列,以空格、制表符或换行符作为分隔符
1、next()会以空格作为分隔符,一行输入1 2 3,只会打印出1
import java.util.Scanner;
public class IOTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
System.out.println(input);
}
}
2、针对输入的一行内容,next()会根据空格、制表符或换行符当成多个输入
import java.util.Arrays;
import java.util.Scanner;
public class IOTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] str = new String[3];
for (int i = 0; i < 3; i++){
str[i] = sc.next();
}
System.out.println(Arrays.toString(str));
}
}
注:nextInt、nextDouble、nextLong等与next()用法类似
二、nextLine()
1、读取一行内容,以换行作为结束
import java.util.Arrays;
import java.util.Scanner;
public class IOTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println(input);
}
}
2、会读取next()、nextInt、nextLong后的换行符
import java.util.Arrays;
import java.util.Scanner;
public class IOTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.next();
String s2 = sc.nextLine();
System.out.println(s1 + s2);
}
}
大家可以试一下,这里有两个输入,next()和nextLine(),但是输入ni后程序就会结束,这是因为nextline()读取了next()后的换行符
如何解决呢?
- 只需在next()后再接一行sc.nextLine()读取换行符即可
import java.util.Arrays;
import java.util.Scanner;
public class IOTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.next();
sc.nextLine();
String s2 = sc.nextLine();
System.out.println(s1 + s2);
}
}
三、应用
如何实现以下输入?
1、
import java.util.Arrays;
import java.util.Scanner;
public class IOTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()){
int n = sc.nextInt();
String[] arrayStr = new String[n];
Long[] arrayLong = new Long[n];
for (int i = 0; i < n; i++){
arrayLong[i] = sc.nextLong();
}
for (int i = 0; i < n; i++){
arrayStr[i] = sc.next();
}
System.out.println(Arrays.toString(arrayLong) + " " + Arrays.toString(arrayStr));
}
}
}
2、输入一个3 * 3的九宫格
- 放入HashSet中
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
public class IOTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
HashSet set = new HashSet();
for (int i = 0; i < n; i++) {
String line = sc.nextLine();
String[] str = line.split(" ");
for (int j = 0; j < str.length; j++){
set.add(str[j]);
}
}
System.out.println(set.size());
}
}
- 放在数组中
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
public class IOTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
sc.nextLine();
int[][] dp = new int[m][n];
for (int i = 0; i < m; i++){
for (int j = 0;j < n; j++){
dp[i][j] = sc.nextInt();
}
}
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
System.out.print(dp[i][j]);
}
System.out.println();
}
}
}