Java中的控制台输出
java中常用的控制台的输入有Scanner和BufferedReade两个。
Scanner的使用如下所示:
import.java.util.Scanner;
// An highlighted block
Scanner scan = new Scanner(System.in);
String str=scan.readline();
//
BufferedReader的使用如下所示:
import.java.io.BufferedReader;
// An highlighted block
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String read=br.readline();
//
我们接着说Scanner使用中的问题:
其中Scanner中有很多的方法,比如:readline();nextInt();next()等等。其中的方法具体查阅API查看吧。
接下首先是大家共所周知的区别
nextLine()方法返回的是Enter键之前的所有字符,可以得到带空格的字符串的。
next()会自动消去有效字符前的空格,只返回输入的字符,不能得到带空格的字符串。
然而!
next()在输入有效字符之后,将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。
nextLine()方法的结束符只是Enter键
因此!
nextLine()自动读取了被next()去掉的Enter作为他的结束符,所以没办法从键盘输入值。
经过验证,其他的next的方法,如nextDouble() ,nextFloat() ,nextInt() 等与nextLine()连用时都存在这个问题。
具体点就是nextLine()不能用在nextInt()的后面!!!!
解决方法有两种
第一种
在每一个 next()、nextDouble() 、nextFloat()、nextInt() 等语句之后加一个nextLine()语句,将被next()去掉的Enter结束符过滤掉。
第二种
把nextLine()改为next()
例如如下代码:
//part1
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();//这里不加nextLine()就会出问题
int x[]=new int[n];
int y[]=new int[n];
for(int i=0;i<n;i++){
String b = sc.nextLine();
String c[]=b.split(",");
x[i]=Integer.parseInt(c[0]);
y[i]=Integer.parseInt(c[1]);
}
//part2
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int x[]=new int[n];
int y[]=new int[n];
for(int i=0;i<n;i++){
String b = sc.next();//这里用next()就可以了
String c[]=b.split(",");
x[i]=Integer.parseInt(c[0]);
y[i]=Integer.parseInt(c[1]);
}
这一段的原文:https://blog.csdn.net/guanghuichenshao/article/details/81545450