Java case study
case 1:AA制
(复习基本数据类型,变量标识符,运算符)
- 假设菜的价格都为整数,定义三个int表示三个菜的价格
- 一共三个人一起吃饭,他们决定AA制
- 请帮他们算出每个人该付多少钱
public class Case1 {
public static void main(String[] args) {
int a = 32;
int b = 20;
int c = 9;
//int result = (a + b + c) / 3;不够精确
double result = (a + b + c) / 3.0; //注意为double否则会损失经度
System.out.println(result);
}
}
case 2:当前时间
(long型,除法,余数,字符拼接)
已知:
System.currentTimeMillis()返回1970-1-1零点至今的毫秒数,long型
- 输出系统的当前时间,格式为时:分:秒
- 限制,不调用系统的Date或Calender API
自写代码:
public class Case2 {
public static void main(String[] args) {
long millis = System.currentTimeMillis();
long totalSecond = millis / 1000;
long Daysecond = totalSecond % 86400;
long hours = Daysecond / 3600;
long minutes = (Daysecond - (hours * 3600)) / 60;
long seconds = (Daysecond - (hours * 3600)) % 60;
System.out.println(millis);
System.out.println((hours + 8) + ":" + minutes + ":" + seconds);
}
}
课程代码:
public class Case2 {
public static void main(String[] args) {
long currentTimeMillis = System.currentTimeMillis();//使用的GMT时间!中国为东8区,所以要在最后在hours上加8!
//总秒数
long totalSeconds = currentTimeMillis / 1000;
//当前秒数
long seconds = totalSeconds % 60;
//总分钟数
long totalMinutes = totalSeconds / 60;
//当前分钟数
long minutes = totalMiuntes % 60;
//总小时数
long totalHours = totalMinutes / 60;
//当前小时数
long hours = totalHours % 24;
System.out.println("系统当前时间是:" + (hours + 8) + ":" + minutes + ":" + seconds);
}
}
case 3:任意范围的随机数
(运算,表达式)
- 已知:Math.random()可以随机返回[0,1)之间的一个double型浮点数
- Math在lang包下,因此不必显示import
- 有办法得到任意范围的随机整数和随机浮点数吗?
产生整数:
public class Case3 {
public static void main(String[] args) {
int a = 1;
int b = 100;
//产生[a,b]的随机整数
//a + random() * (b - a + 1)
int r = a + (int) (Math.random() * (b - a + 1));
System.out.println("产生的随机整数是:" + r);
}
}
产生浮点数:
public class Case3 {
public static void main(String[] args) {
int a = 1;
int b = 100;
double r = a + Math.random() * (b - a + 1);
System.out.println("产生的随机浮点数是:" + r);
}
}
常见错误
- 注意声明变量以及初始化变量(注意阅读编译错误提示)
- 整数溢出(常见于byte = 127+ & byte = -128- 统一使用int)
- 取整错误(逻辑上区间开闭关系)
- 整数除法(浮点数到整数将会被自动取整)