今天做了个笔试题,题难度还好,就是需要自己输入测试用例。做牛客与LeetCode()都不用管这,自己好久没练习了,折腾半天。
特总结一下。
1.控制台输入多行数,不输入时回车换行停止。
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("#"))
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
ArrayList<String> list = new ArrayList<String>();
String s = "";
**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,next(),hasNext()
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()方法跳出while循环的方法:设置一个终止符号if(s.equals("#")) break;
next(),nextInt 输入遇到空格,回车换行就算结束
next返回的是字符串
nextInt 是整型
测试next()
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
来源:CSDN
作者:大鹏视界U
链接:https://blog.csdn.net/qq_14842117/article/details/89007015