题目要求————
代码以及运行截图~
写入文件
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class test {
public static void main(String[] args) {
BufferedWriter out=null;
try {
out=new BufferedWriter(new FileWriter("D:\\Salary.txt"));
for(int i=0;i<1000;i++)
{
out.write("FirstName"+(i+1)+"LastName"+(i+1)+random()+"\n");
}
out.flush();
System.out.println("写入成功");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String random(){
Random r=new Random();
int x=r.nextInt(3);
// System.out.println(x);
// System.out.println(x);
switch (x)
{
case 0:
String a="assistant";
double salaryA=50000+r.nextDouble()*40000;
while (salaryA>80000)
{
salaryA=50000+r.nextDouble()*40000;
}
return a+" "+String.format("%.2f",salaryA);
case 1:
String b="associate";
double salaryB=60000+r.nextDouble()*60000;
while (salaryB>110000)
{
salaryB=60000+r.nextDouble()*60000;
}
return b+" "+String.format("%.2f",salaryB);
case 2:
String c="full";
double salaryC=75000+r.nextDouble()*70000;
while(salaryC>130000)
{
salaryC=75000+r.nextDouble()*70000;
}
return c+" "+String.format("%.2f",salaryC);
default:return "sb";
}
}
}
读取文件
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
/**
* Created with IntelliJ IDEA.
*
* @Auther: 风离
* @Date: 2020/12/17/0:23
* @Description:
*/
public class test3 {
public static double sum1=0;
public static double sum2=0;
public static double sum3=0;
public static int count1=0;
public static int count2=0;
public static int count3=0;
public static void main(String[] args) throws IOException {
BufferedReader in=new BufferedReader(new FileReader("D:\\Salary.txt"));
for(int i=0;i<1000;i++)
{
String x[]=in.readLine().substring(18).split(" ");
if(x[0].contains("assistant"))
{
sum1+=Double.parseDouble(x[1]);
count1++;
}
if(x[0].contains("associate"))
{
sum2+=Double.parseDouble(x[1]);
count2++;
}
if(x[0].contains("full"))
{
sum3+=Double.parseDouble(x[1]);
count3++;
}
}
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("assistant "+"职工数:"+count1+" 总薪水:"+df.format(sum1)+" 平均薪水:"+ df.format(sum1/count1));
System.out.println("associate "+"职工数:"+count2+"总薪水:"+df.format(sum2)+" 平均薪水:"+df.format(sum2/count2));
System.out.println("full "+"职工数:"+count3+"总薪水:"+df.format(sum3)+" 平均薪水:"+df.format(sum3/count3));
}
}
测试截图