注意事项:
1、提交代码时不要添加任何注释,否则容易造成编译错误。
一、读取输入并赋值
输入的第一行包含了两个整数n, k,第二行包含n个正整数,如:
6 9
2 6 5 6 3 5
情况一:第二行数据顺序访问,且只使用一次。(无需创建数组)——真题实例
int n, k, count = 0, temp, sub = 0;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
k = sc.nextInt();
for (int i = 0; i < n; i++) {
temp = sc.nextInt();
//TODO
}
情况二:第二行数据可能需要按索引重复访问。(创建数组)
int n, minq, count = 0;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
minq = sc.nextInt();
int[] im = new int[n];
for (int i = 0; i < im.length; i++) {
im[i] = sc.nextInt();
}
注意:
若输入一个整数n后,再换行输入n行字符串,则sc.nextLine()读入整数,而不应该使用sc.nextInt()读入,否则,在循环读入n行字符串时,第1行数据会读入空串,导致程序逻辑错误。因为,nextInt()只读取了数字n却没有读取换行符,下一个nextLine()会读取换行符并解析为空串。
如果要读入:
2
xxxxx
xxxxxxx
则使用代码段如下:
Scanner sc = new Scanner(System.in);
int n = Integer.valueOf(sc.nextLine());
for (int i = 0; i < n; i++) {// 权限赋值
String s = sc.nextLine();
//TODO
}
二、选用合适的数据结构
三、排序——真题实例
int n;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
// 输入数据
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
Arrays.sort(a);// 排序