一、基本语句
1.输入
Scanner reader = new Scanner(System.in) ;
读一个整数
int n = sc.nextInt();
读一个字符串
String s = sc.next();
读一个浮点数
double t = sc.nextDouble();
读一整行
String s = sc.nextLine();
判断是否有下一个输入
sc.hasNext()
sc.hasNextInt()
sc.hasNextDouble()
sc.hasNextLine()
2.输出
System.out.print();
System.out.println();
System.out.format();
System.out.printf();
情况一:不知道有多少行输入(或者多测试用例)。如果是先获取所有输入,再集中处理,使用ctrl+D结束输入。
输入:11001
11111
Scanner sc = new Scanner(System.in);
ArrayList<String> arrayList = new ArrayList<>();
while (sc.hasNext()){
arrayList.add(sc.next());//nextLine()/next()看情况使用
}
情况二:一行输入,略
情况三:输入为0结束输入
while ((num = sc.nextInt()) != 0){
.....
}
情况四:空行结束输入
while (true){
String s = sc.nextLine();
if(s.equals(""))
break;
}
情况五,你知道有几行输入
Scanner in = new Scanner(System.in);
int n =in.nextInt();//n表示下面的输入行数
ArrayList<String> arr = new ArrayList<>();
While(n-- > 0){
arr.add(in.next());
}
//格式
//2
//5
//1 2 4 5 6
//6
//1 2 3 4 5 6
Scanner reader = new Scanner(System.in);
int m = reader.nextInt();
for (int i=0 ; i<m ; i++) {
int n = reader.nextInt() ;
int [] array = new int[n] ;
for (int j = 0; j < n; j++) {
array[j] = reader.nextInt();
}
}
情况六? 记得有次输入以空行结束,但是输入必须下面这样,我也不懂
Scanner sc = new Scanner(System.in);
ArrayList<String> arrayList = new ArrayList<>();
while (sc.hasNext()){
String s = sc.nextLine();
if(s.equals("EOF"))
break;
arrayList.add(s);
}
其他参考:
https://www.cnblogs.com/rrttp/p/8715731.html
https://blog.youkuaiyun.com/qq_42320048/article/details/92615424