随笔,今天写代码遇到的问题
Scanner reader =new Scanner(System.in);
int b=reader.nextInt();
String str=reader.nextLine();
System.out.println("here");
int a=reader.nextInt();
System.out.println(b+str+a);
运行结果,输入b为1回车后自动输出here,回车被nextLine当做结束符,nextLine获得的为空白:
1
here
2
12
进程完成,退出码 0
解决方法:
①next()方法代替
② 加一个额外的nextLine。
Scanner reader =new Scanner(System.in);
int b=reader.nextInt();
reader.nextLine();
String str=reader.nextLine();
System.out.println("here");
int a=reader.nextInt();
System.out.println(b+str+a);
运行结果:
1
2
here
3
123
进程完成,退出码 0
搜到的这篇博文写的清楚点
(https://blog.csdn.net/SummerJX/article/details/79872140)
2019.4.22 补充
import java.util.*;
public class test{
public static void main(String[] args){
Scanner reader=new Scanner(System.in);
for(int i=0;i<3;i++){
String str=reader.nextLine();
System.out.println(i+str);
}
}
}
运行结果:
与
0与
或
1或
非
2非
在这个循环过程中就不需要加额外的nextLine()来吞回车,不然会出问题。