java基础题,在线等,急!

设计一个货船类CargoBoat,该类有最大的装载量1000吨,每次可装载0到500吨货物,假设初始状态货船空的,一次次往里面随机装载物品,如果超出最大的装载量则提示超重(用异常表示)

import java.io.*;import java.util.*;public class T09 { public static void main(String[] args) throws IOException{ outFile(new File("D:\\demo")); //调用outFile方法 } public static void outFile(File file) throws IOException{ File[] files = file.listFiles(); //获取该文件夹中所有的文件和文件夹 BufferedWriter bos = new BufferedWriter(new FileWriter("d:\\a.txt")); //字符输出流,保存到d:\\a.txt TreeMap<String,Integer> tm = new TreeMap<String,Integer>(); //定义一个TreeMap来记录文件后缀名和出现的次数 for(File f : files){ if(f.isFile()){ //判断是否是文件,我们只对文件进行获取,文件夹不管 String[] str = f.getName().split("\\."); String suffix = "."+str[str.length-1]; //获取文件的后缀名 if(tm.containsKey(suffix)){ //判断tm中是否包含该后缀名,如果包含就把该后缀名的出现次数取出然后加1,再存入进去 int conut = tm.get(suffix); //取出出现的次数 tm.put(suffix,++conut); //重新存入出现的次数 } else{ tm.put(suffix,1); //如果没有包含该后缀名,就说明是第一次出现,然后就存入改后缀名,次数为1 } } } Set<Map.Entry<String,Integer>> set = tm.entrySet(); //把TreeMap转换成Set Iterator<Map.Entry<String,Integer>> it = set.iterator(); //获取迭代器 while(it.hasNext()){ //迭代取值 Map.Entry<String,Integer> map = it.next(); //获取整个元素 String key = map.getKey(); //获取元素中的键 int value = map.getValue();//获取元素中的值 bos.write(key+" "+value); //存入键和值到文件中 bos.newLine(); //存入换行 } bos.close(); //关闭并刷新输出流 }}
温馨提示:答案为网友推荐,仅供参考