几种输入方式:
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
readLine() 遇到回车换行算截止
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
ArrayList<String> list = new ArrayList<String>();
String s = "";
//如果是让遇到#截止,则改为: while(!(s = bf.readLine()).equals("#"))
while(!(s = bf.readLine()).equals("")) {
list.add(s);
}
for(int i = 0;i<list.size();i++) {
System.out.println(list.get(i));
}
输入:
fafa
fafa
fadfa
faf#
#
输出:
fafa
fafa
fadfa
faf#
Scanner
比较常用的几个方法:
nextLine()
nextInt
hasNext()
next()
nextLine()
nextLine()空格也算输入,遇到回车换行停止
ArrayList<String> list = new ArrayList();
Scanner sc = new Scanner(System.in);
String s = "
while(!(s=sc.nextLine()).equals("")) {
list.add(s) ;
}
for(String ss:list) {
System.out.println(ss);
}
//控制台输入运行结果
13 3 3
343 34 34 34
34 34
13 3 3
343 34 34 34
34 34
hasNext()
hasNext()方法跳出while循环的方法:设置一个终止符号if(s.equals("#")) break;
ArrayList<String> list = new ArrayList();
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String s = sc.next();
if(s.equals("#")) break;
list.add(s);
}
for(String ss:list) {
System.out.println(ss);
}
运行效果展示:
fdsa
faf
fdaf
#
fdsa
faf
fdaf
nextInt()
ArrayList<Integer> list = new ArrayList();
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
int n = sc.nextInt();
if(n == 0) break;//假设输入0停止
list.add(n);
}
for(Integer ss:list) {
System.out.println(ss);
}
运行效果展示1:
1
23 3
5
3
0
1
23
3
5
3
运行效果展示2:
1 2 3 4 5 0
1
2
3
4
5
运行效果展示3:
1
2
3
4
5
0
1
2
3
4
5