薪水计算器
要求:键盘输入月薪,输出年薪,直至键盘输入’exit’,退出程序;中途输入’next’,退出计算,计算下一个
Scanner sc = new Scanner(System.in);
while(true){
try {
System.out.print("请输入您的月薪:(next表示下一个人,exit表示退出)");
String str = sc.nextLine().strip();
if(str.equals("exit")){
break;
}else if(str.equals("next")){
continue;
}else {
double salary = Double.parseDouble(str);
System.out.print("请输入月份数:");
String mon = sc.nextLine();
double month = Double.parseDouble(mon);
salary *= month;
if(salary>10_0000){
System.out.println("恭喜您,年薪"+salary+"元, 过十万啦!");
}else {
System.out.println("您的年薪是"+salary+"元");
}
}
}catch (Throwable e){
System.out.println("输入的内容无法处理哦!");
System.out.println(e);
}
}
注意
nextInt()后接nextLine()会直接跳过,因为nextInt把数字取走后,留下换行符,被nextLine获取
解决方法:
方法1. 增加一行nextLine获取换行符
方法2. 用nextLine获取后进行数字转换和异常处理(如上代码)
容器存放随机数
要求:创建30个[1,100]的不重复随机整数,用容器存放
List实现
List<Integer> list = new ArrayList<>();
while(true){
int num = (int)(Math.random()*100+1);
if(!list.contains(num))
list.add(num);
if(list.size()==30)
break;
}
Set实现
Set<Integer> set = new HashSet<>();
while(true){
int num = (int)(Math.random()*100+1);
set.add(num);
if(set.size()==30)
break;
}
HashSet存放整数时可能会出现假排序的现象(随机产生的数但输出时是有序的):
因为Integer的hashCode方法返回的哈希值就是值本身