import java.io.*;
import java.util.HashMap;
import java.util.Scanner;
public class orde {
public static void main(String args[]) throws IOException {
Scanner c1=new Scanner(new FileReader(new File("students.txt")));
Scanner c2=new Scanner(new FileReader(new File("course1.txt")));
Scanner c3=new Scanner(new FileReader(new File("course2.txt")));
HashMap<String,String> M1=new HashMap<String,String>();
HashMap<String,String> M2=new HashMap<String,String>();
HashMap<String,String> M3=new HashMap<String,String>();
add(c1,M1);
add(c2,M2);
add(c3,M3);
for(String key:M1.keySet()) {
if(M2.containsKey(key))
System.out.println(key+" "+M1.get(key)+" "+ "course1:"+ " " + M2.get(key)+ " " + "course2:"+ " " + M3.get(key));
}
}
private static void add(Scanner c1,HashMap<String, String> M) {
while(c1.hasNext()) {
String S[]=c1.nextLine().split(" ");
M.put(S[0],S[1]);
}
}
}
输出是这样的:
25212 Greg IR101: 70.5 IR102: 72.5
25954 Betty IR101: 70.2 IR102: 63.4
25321 Elsie IR101: 51.5 IR102: 45.6
25654 Chris IR101: 58.6 IR102: 35.1
基本上我使用散列连接将三个文件连接在一起,一个包含学生ID和名称,课程1包含模块1的标记,课程2包含模块2的标记,但是我是在尝试计算两个标记(M2和M3)的平均值时遇到问题,例如它在完成时应如下所示:
25212 Greg IR101: 70.5 IR102: 72.5 Average: 71.5
25954 Betty IR101: 70.2 IR102: 63.4 Average: 66.8
答案 0 :(得分:0)
当你将你的价值观作为字符串时,你可以将它们解析为双打:
String myString = "70.5";
double x = Double.parseDouble(myString);
现在你可以用它来计算平均值
String s1 = "70.5";
String s2 = "72.5";
double m = (Double.parseDouble(s1)+Double.parseDouble(s2))/2d;
System.out.println(m);
请注意,如果您尝试解析的值不是数字,则可能会出错 即
String myString="test";
double x = Double.parseDouble(myString); // error
对于您的案例一个小例子:
public static void main(String[] args){
HashMap<String,String> M1=new HashMap<String,String>();
HashMap<String,String> M2=new HashMap<String,String>();
HashMap<String,String> M3=new HashMap<String,String>();
M1.put("222", "Greg");
M2.put("222","70.5");
M3.put("222", "72.5");
for(String key:M1.keySet()) {
if(M2.containsKey(key)){
double average = (Double.parseDouble(M2.get(key))+Double.parseDouble(M3.get(key)))/2d;
System.out.println(key+" "+M1.get(key)+" "+ "course1:"+ " " + M2.get(key)+ " " + "course2:"+ " " + M3.get(key)+" average:"+average);
}
}
}