Scanner 是一个类,scanner 变量保存的是对象的引用:
Scanner scanner = new Scanner(System.in);可以分成四部分理解:
Scanner scanner new Scanner(System.in)变量的类型 变量名 创建对象 调用构造方法为什么数组需要 new
即使数组中保存的是 int,数组整体仍然属于引用类型:
int[] scores = new int[10];int[] scores:声明一个整数数组变量。new int[10]:真正创建一个包含10个位置的数组。
String studentName = scanner.nextLine(); studentNames[studentCount] = studentName; 实际后端开发也经常采用: 接收数据 → 校验数据 → 保存数据
- 容量被写死为10 if (studentCount == 10) 如果以后把容量改成20,这里还要再次修改。
提示:使用数组本身的长度,并考虑用 >= 防御异常数据:
if (studentCount >= studentNames.length) scanner.nextInt();只读取数字,不会取走后面的回车 需要注意如果还有下一次调用,需要使用,scanner.nextLine()读取空字符串
main 中的 studentCount 和方法参数 studentCount 是两个不同的局部变量。调用方法时,Java把整数值复制给方法参数,所以方法内部自增只改变副本。return studentCount 把更新后的值返回给调用者,调用者再通过赋值更新 main 中的变量。
2 成绩统计中为什么要写成三个独立的 if: if (scores[index] > maxScore) { maxScore = scores[index]; }
if (scores[index] < minScore) { minScore = scores[index]; }
if (scores[index] >= 60) {
passCount++;
}
而不应该写成:
if (scores[index] > maxScore) {
maxScore = scores[index];
} else if (scores[index] < minScore) {
minScore = scores[index];
} else if (scores[index] >= 60) {
passCount++;
}
else-if 表示几个条件互斥,一次只执行一个分支。但最高分、最低分和是否及格是互相独立的统计,一个成绩可能既刷新最高分又属于及格成绩,因此必须使用多个独立的 if。
3,容量为10的数组
如果只添加两名学生却遍历数组全部长度,会输出什么?
String[] 未赋值的位置默认是 null,int[] 未赋值的位置默认是 0,因此可能输出:
- 姓名:张三,成绩:85
- 姓名:李四,成绩:90
- 姓名:null,成绩:0
- 姓名:null,成绩:0 ……
- 姓名:null,成绩:0
下面代码不能编译:
if (true) {
int score = 90;
}
System.out.println(score);
score 定义在 if 的大括号内,作用域只到该代码块的右大括号为止。离开代码块后,Java找不到这个变量,通常提示:
cannot find symbol 外部不能访问内部
public static void searchStudentByName(
Scanner scanner,
String[] studentNames,
int[] scores,
int studentCount
) {
boolean isFound = false;
System.out.print(“请输入要查询的学生姓名:”);
String searchName = scanner.nextLine();
for (int index = 0; index < studentCount; index++) {
if (studentNames[index].equals(searchName)) {
System.out.println(“查询成功,姓名:” + studentNames[index] + “,成绩:” + scores[index]);
isFound = true;
break;
}
}
if (!isFound) {
System.out.println(“查无此人”);
}
}
容易忘的 scanner.nextInt();后面的scanner.nextLine(); 以及scanner的关闭
一些interiJ ide的快捷键
ctrl +d 复制光标所在行内容到下一行 ctel + y 删除光标所在行内容 ctrl shift +折叠当前文件的全部方法 选中 ctrl+alt+l 格式化