Java: 根据字母的字母顺序创建 int 值

Java: creating int value based on letters alphabetical position

我的thoughts/Questions: 我正在进行 Java 挑战(说明如下)。我已完成 第 1 部分(如下面的代码所示)。但是,我很难在 第 2 部分 上取得进展。我很想听听 suggestions/examples 告诉我如何完成这个挑战。此外,如果需要,可以重构我在第 1 部分的工作。

挑战方向:

使用 names.txt 文件,这是一个 46K 的文本文件,包含在资源目录中找到的超过五千个名字。

第 1 部分: 首先按字母顺序对列表进行排序。在答案目录中将此新文件另存为 p4aNames.txt。

第 2 部分: 使用 p4aNames.txt,取每个名字的字母顺序值,并将该值乘以其在列表中的字母顺序位置以获得名字分数。例如,当列表按字母顺序排序时,COLIN 的值为 3 + 15 + 12 + 9 + 14 = 53,是列表中的第 938 个名称。因此,COLIN 将获得 938 × 53 = 49714 的分数。将所有名称分数的列表保存为 p4bNames.txt.

第 3 部分:文件中所有名字的总分是多少?

图片 Link 显示输出和目录:

http://screencast.com/t/t7jvhYeN

我的当前代码:

package app;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

public class AlphabetizedList {
 public static void main() throws IOException {
  new AlphabetizedList().sortingList();
 }
 public void sortingList() throws IOException {
  FileReader fb = new FileReader("resources/names.txt");
  BufferedReader bf = new BufferedReader(fb);
  String out = bf.readLine();
  out = out.substring(out.indexOf("\"")); //get rid of strange characters appearing before firstname 
//  System.out.println(out); Would show unsorted names
  bf.close();
  fb.close();
  
  String[] sortedStr = out.split(",");
  Arrays.sort(sortedStr);
  
  PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("answers/p4aNames.txt")));
  for (int i = 0; i < sortedStr.length; i++) {
  pw.println(sortedStr[i]);
  System.out.println(sortedStr[i]); // print to console just to see output
  }
  pw.close();
 }
}

您在计算每个字符的数值时遇到困难?只需将字符串转换为大写,将每个字符转换为 int,然后减去 64 即可得到每个字符的数值。像这样:

int score = 0;
for (char ch: sortedStr[i].toUpperCase().toCharArray()) {
     score += (int)ch - 64;  /* A is decimal 65 */
}
score = score * i; /* multiply by position in the list */

您可以尝试使用资源,这样您就不必使用 file.close ..

显式关闭文件
try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("answers/p4bNames.txt")))) {
        for (int i = 1; i <= sortedStr.length; i++) {//starting from1
            int score = 0;
            for (char ch : sortedStr[i-1].toUpperCase().toCharArray()) {
                score += ch - 'A' + 1;  //subtracting A for ex if ch is C then C - A will be 2 so adding 1 to make 3
            }
            score *= i;//mutiplying the value by the index
            pw.println(score);
            System.out.println(sortedStr[i]); // print to console just to see output
        }
    } catch (IOException ex) {
        //Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
    }