Scanner方法
核心是单行输入字符串,切割字符串中的空格,存入数组
Scanner s = new Scanner(System.in);
String inputStr = s.nextLine();
String[] strArray = inputStr.split(" ");
int[] num = new int[strArray.length];
for(int i = 0 ; i < num.length ; i++){
num[i] = Integer.parseInt(strArray[i]);
}
Scanner输入的一个问题:在Scanner类中如果我们在任何7个nextXXX()方法之后调用nextLine()方法,这nextLine()方法不能够从控制台读取任何内容,并且,这游标不会进入控制台,它将跳过这一步。nextXXX()方法包括nextInt(),nextFloat(), nextByte(),nextShort(),nextDouble(),nextLong(),next()。此时应该使用BufferedReader。 ?
BufferedReader方法
首行输入数组大小,次行输入数组内容,依次用空格隔开。
它的优势在于消耗比scanner更少的内存和时间,如果在写算法时优先使用BufferedReader方法。
注意:使用完记得close,Scanner方法不需要close。
public static int[] ListInput() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = 0;
String str = null;
N= Integer.parseInt(br.readLine());
str = br.readLine();
br.close();
int[] myList = new int[N];
String[] strArray = str.split(" ");
for (int i = 0; i < N; i++) {
myList[i] = Integer.parseInt(strArray[i]);
}
return myList;
}
···