一列日,一列数值
要求如图,希望有空的前辈能花点时间帮忙写一下,非常感激!
需要再增加一个功能,输入日期,就能显示对应日期的数字总合
public static Map<String, Integer< countDate(String filePath) {
Map<String, Integer< map = new HashMap<String, Integer<();
FileInputStream in = null;
try {
//filepath为文件路径
in = new FileInputStream(filePath);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while(true) {
//按行读取
String str = br.readLine();
if (str == null) break;
if ((str = str.trim()).length() == 0) continue;
str = str.replaceAll("\s+", " ");
String[] result = str.split(" ");
Integer v = map.get(result[0]);
v = v == null ? Integer.valueOf(result[1]) : v.intValue() + Integer.parseInt(result[1]);
map.put(str, v);
}
Iterator<String> iterator = map.keySet().iterator();
while(iterator.hasNext()) {
String key = iterator.next();
System.out.println("date="+key+",totalCount="+map.get(key));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return map;
}
public static void read(String filePath) {
Map<String, Integer< map = countDate(filePath);
System.out.print("请输入日期:");
Scanner in = new Scanner(System.in);
try {
String date = in.nextLine();
Integer count = map.get(date);
int c = count == null ? 0 : count.intValue();
System.out.println("该日期下的总数为:" + c);
} catch (Exception e) {
e.printStackTrace();
}
}
把第一个方法改为有返回值的,然后main调用第二个方法就可以
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
public static void countDate(String filePath) {
Map<String, Integer> map = new HashMap<String, Integer>();
FileInputStream in = null;
try {
//filepath为文件路径
in = new FileInputStream(filePath);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while(true) {
//按行读取
String str = br.readLine();
if (str == null) break;
if ((str = str.trim()).length() == 0) continue;
str = str.replaceAll("\s+", " ");
String[] result = str.split(" ");
Integer v = map.get(result[0]);
v = v == null ? Integer.valueOf(result[1]) : v.intValue() + Integer.parseInt(result[1]);
map.put(str, v);
}
Iterator<String> iterator = map.keySet().iterator();
while(iterator.hasNext()) {
String key = iterator.next();
System.out.println("date="+key+",totalCount="+map.get(key));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
如果有帮助,希望结帖