文件names.txt (右键另存为)是一个46K大小的文本文件,包含5000多个英文名字。利用这个文件,首先将文件中的名字按照字母排序,然后计算每个名字的字母值,最后将字母值与这个名字在名字列表中的位置相乘,得到这个名字的得分。
例如将名字列表按照字母排序后, COLIN这个名字是列表中的第938个,它的字母值是3 + 15 + 12 + 9 + 14 = 53。所以COLIN这个名字的得分就是938 53 = 49714.
文件中所有名字的得分总和是多少?
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
public class Test {
public static StringBuilder s = new StringBuilder();
public static void readFile(String filePathAndFileName) throws Exception {
FileInputStream fis = new FileInputStream(new File(filePathAndFileName));
byte[] b = new byte[1];
int len = fis.read(b);
while (len != -1) {
s.append(new String(b));
len = fis.read(b);
}
}
public static void main(String[] args) throws Exception {
readFile("d:/names.txt");
String[] str = s.toString().replace("\"", "").split(",");
Arrays.sort(str);
long total = 0;
long stemp = 0;
for (int i = 0; i < str.length; i++) {
for (int j = 0; j < str[i].length(); j++) {
stemp += str[i].charAt(j) - 64;
}
total += stemp * (i + 1);
stemp = 0;
}
System.out.println("总和为:" + total);
}
}