Java作业总结-5、6章

系列 - JAVA作业总结
目录
二月天、库存管理系统、删除不及格成绩这三份作业的总结和注意事项
案例5-5 二月天
再次熟悉一下三目运算符,三目运算符可以看作是if-else的简化版,用一个打分的例子来解释:
// 判断成绩是否及格
int score = 75;
// 普通if-else写法
String result;
if(score >= 60) {
result = "及格";
} else {
result = "不及格";
}
// 三目运算符写法
String result = score >= 60 ? "及格" : "不及格";
三目运算符的格式
条件 ? 值1 : 值2
可以理解为:
- 如果条件为true,就取值1
- 如果条件为false,就取值2
import java.time.LocalDate;
import java.util.Scanner;
public class demo55 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println("请输入要判断的年份:");
int year = scn.nextInt();
System.out.println("方法一:" + year + "的2月有" + getNumOfDaysInFeb1(year) + "天");
System.out.println("方法二:" + year + "的2月有" + getNumOfDaysInFeb2(year) + "天");
}
/**
* 思路一
* @param year 年份
* @return 2月的天数
*/
public static int getNumOfDaysInFeb1(int year) {
LocalDate date = LocalDate.of(year, 3, 1);
LocalDate feb = date.minusDays(1);
return feb.getDayOfMonth();
}
/**
* 思路二
* @param year 年份
* @return 2月的天数
*/
public static int getNumOfDaysInFeb2(int year) {
LocalDate date = LocalDate.of(year, 1, 1);
if (date.isLeapYear()) {
return 29;
} else {
return 28;
}
// 这种写法可以
// return date.isLeapYear() ? 29 : 28;
}
}
思考:计算绝对值
int num = -5;
int abs = ?; // 补全代码
- 不要嵌套太多三目运算符,会导致代码可读性变差
- 复杂的判断逻辑还是建议用if-else
案例6-1 库存管理系统
1、使用迭代器遍历(作业要求)
// 使用迭代器遍历商品
static void showWareHouse() {
System.out.println("==========================");
Iterator iterator = goodsList.iterator();
while (iterator.hasNext()) {
Goods goods = (Goods) iterator.next(); // 类型转换(Object->Goods)
System.out.println(goods);
}
System.out.println("==========================");
}
2、使用 foreach 循环遍历
static void showWareHouse() {
System.out.println("==========================");
for (Object obj : array) {
System.out.println(obj);
}
System.out.println("==========================");
}
3、添加商品时可以使用匿名对象
// 商品入库
static void addGoods() {
Scanner sc = new Scanner(System.in);
System.out.print("商品名称:");
String name = sc.next();
System.out.print("商品价格:");
double price = sc.nextDouble();
System.out.print("商品数量:");
int num = sc.nextInt();
// Goods g = new Goods(name, price, num);
// goodsList.add(g);
goodsList.add(new Goods(name, price, num));
}
作业6-1 删除不及格成绩
课上演示的做法是:
for (int i = 0; i < list.size(); i ++) {
if (list.get(i) < 60) {
list.remove(i);
i --;
}
}