1、next()与nextLine()
(1) next():
- 一定要读取到有效字符后才可以结束输入;
- 对输入有效字之前遇到的空格,next()方法会自动将其去掉;
- 只有输入有效字符后才能将其后面输入的空格作为分隔符或结束符。当有效字符出现后,后面的再输入空格,那么空格后的元素就不再输出;
- next()不能得到带有空格的字符串;
(2) nextLine():
- 以Enter为结束符,可以返回输入回车之前的所有字符;
- 可以获得空格;
next()会丢掉空格,nextLine()不会丢掉空格。
2、把键盘输入1 2 3 4转为数组
Scanner str1=new Scanner(System.in);
String sc=str1.nextLine();
String[] arr=sc.split(" ");
int[] List1=new int[arr.length];
for(int j=0;j<arr.length;j++) {
List1[j]=Integer.parseInt(arr[j]);
}
3、把键盘输入1 2 3 4转为数组另一种
Scanner sc = new Scanner(System.in);
int[] nums = new int[3];
for (int i = 0; i < 3; i++) {
nums[i] = sc.nextInt();
}
Scanner sc = new Scanner(System.in);
int n = Integer.valueOf(sc.next()).intValue(); // int n = sc.nextInt();
int[] arry = new int[n];
for (int i = 0; i < arry.length; i++) {
arry[i] = sc.nextInt();
}
如果是long可以nextLong();
如果是逗号分割,需要使用上一种方法