练习请移步这里:https://www.acmcoder.com/ojques.html?id=64568738ea2ce53399dcc626
读取整数数组
需要先接受数组大小,再接受数组中每个元素的值 。
示例代码 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| public class Main { public static void main(String args[]) {
Scanner cin = new Scanner(System.in);
int numLen = cin.nextInt(); int[] numArr = new int[numLen]; for (int i = 0;i < numLen ; i ++) { numArr[i] = cin.nextInt();
} Solution solution = new Solution(); int[] res = solution.process(numArr); System.out.println(Arrays.toString(res));
} }
class Solution{ public int[] process(int[] nums){ int[] res = nums; return res ; } }
|
读取字符串数组
大致方法和读取整数数组差不多,都是先输数组大小、再输数组内容,但是要注意 数字到字符串要换行
读取字符串分为两种 :
- 这个字符串包括空格 “ ” 。 比如字符串s = “hello paopao !” 。
使用 nextLine()
,可以读取空格的字符串,使用前判断 hasNextLine()
,
这个字符串包括空格 。 那么上面同样的输入 ,就期望得到三个字符串 。 s1 = “hello” ,s2 = “paopao” , s3 = “!”
使用 next()
,只能读取到空格之前的字符串 ,使用前判断 hasNext()
举例 :
- 输入 “hello paopao !” 和 “ok paopao ?”两个字符串 ,两行输入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class Main { public static void main(String args[]) {
Scanner cin = new Scanner(System.in); int strLen = cin.nextInt(); cin.nextLine() ; String[] strArr = new String[strLen]; int j = 0; while(cin.hasNextLine() && j < strLen){ strArr[j] = cin.nextLine(); j ++; } System.out.println(Arrays.toString(strArr));
} }
|
2 .输入 “paopao” “is” “pig” 三个字符串 ,一行输入,中间用空格分开
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class Main { public static void main(String args[]) {
Scanner cin = new Scanner(System.in); String[] strArr = cin.nextLine().split(" "); System.out.println(Arrays.toString(strArr));
} }
|
一个不太聪明的法子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class Main { public static void main(String args[]) {
Scanner cin = new Scanner(System.in); int strLen = cin.nextInt(); cin.nextLine() ; String[] strArr = new String[strLen]; int j = 0; while(cin.hasNextLine() && j < strLen){ strArr[j] = cin.nextLine(); j ++; } System.out.println(Arrays.toString(strArr));
} }
|