1、单行输入
// 本题为考试单行多行输入输出规范示例,无需提交,不计分。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {// 注意,如果输入是多个测试用例,请通过while循环处理多个测试用例
int a = in.nextInt();
int b = in.nextInt();
System.out.println(a + b);
}
}
2、 多行输入
- 例1
// 本题为考试多行输入输出规范示例,无需提交,不计分。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int ans = 0, x;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
x = sc.nextInt();
ans += x;
}
}
System.out.println(ans);
}
}
- 例2
有个题输入的是两行数组和一个整数(整数在最后),但是没给每一行数组元素个数,nextLine()整行读取再切分
publicstaticvoidmain(String[] args) {
Scanner sc = newScanner(System.in);
String str = sc.nextLine().toString();
int[] dis = getIntArr(str);
str = sc.nextLine().toString();
int[] eng = getIntArr(str);
int maxDis = sc.nextInt();
}
static int[] getIntArr(String str){
String[] arr = str.split(" ");
int[] b = new int[arr.length];
for(int j = 0; j<b.length;j++) {
b[j] = Integer.parseInt(arr[j]);
}
return b;
}
- 例3
//输入描述:
//输入包括2行:
//第一行为整数n(1 <= n <= 50),即抹除一个数之后剩下的数字个数
//第二行为n个整数num[i] (1 <= num[i] <= 1000000000)
import java.util.*;
public class Next {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
int[] num = new int[N];
for (int i = 0; i < N; i++) {
num[i] = sc.nextInt();
}
//System.out.println("hallo");
}
}
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
char[] arr = str.toCharArray();
}
}