2015-06-26 29 views
-1

我的想法/问题: 我正在研究Java挑战(DirectionsBowow)。我已完成第1部分(如下面的代码所示)。但是,我很难与第2部分取得进展。我有兴趣听到关于如何完成这一挑战的建议/示例。以及,如果需要,我可能会重构第1部分的工作。Java:基于字母的字母位置创建int值

挑战路线:

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

第1部分:首先将列表按字母顺序排序。将这个新文件保存为answers目录中的p4aNames.txt。

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

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

产品图的链接显示输出&目录:

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

+0

StackOverflow的是不是一个真正的平台,在这里,你可以请求其他人完全编写你的代码。编写你自己的代码,如果你坚持不懈,回来,但请展示一些更多的努力。你对第2部分有什么不了解? – Alexander

回答

1

你在计算每个角色的数字值时遇到困难?只需将该字符串转换为大写,将每个字符转换为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 */ 
0

您可以使用的资源尝试,这样你就不必使用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); 
    }