我的想法/问题:
我正在开展Java挑战(方向吼叫)。我已完成第1部分(如下面的代码所示)。我非常接近 Part 2/3 完成。
正如您在我的代码中看到的,我有2个for循环。第一个,遍历我的排序名称数组。第二,迭代每个名字中的字符。
如说明中所述,将为每个字符生成一个int值,然后添加这些值。因此,A为1,B为2,C为3 ...... ABC为6.然后将此int值乘以给定String / name的索引号。因此,如果ABC(值为6)位于索引2,则其得分为12。
完成上述步骤后,我将得出所有得分(每个得分)。
以上是我对方向的理解。
问题是我的输出如下所示:
"AARON"
0
"ABBEY"
-25
"ABBIE"
-82
"ABBY"
-90
"ABDUL"
-80
"ABE"
-260
"ABEL"
-240
"ABIGAIL"
-133
"ABRAHAM"
-128
"ABRAM"
-225
"ADA"
-540
"ADAH"
-506
"ADALBERTO"
216
"ADALINE"
-182
"ADAM"
-574
"ADAN"
-600
"ADDIE"
-592
"ADELA"
-629
我已经完成了几次我的逻辑,这对我来说似乎是正确的,但我不知道我是如何生成这些数字的。我唯一的想法是引号(“)丢失了我的计算。它们的ASCII值为34.我试图在我的代码中的多个地方用replace()& replaceAll()删除它们,但我也没能。
我做错了什么/如何解决/我需要做什么才能完成此任务/如何改进我的代码?
挑战方向:
使用names.txt文件,这是一个包含资源目录中超过五千个名字的46K文本文件。
第1部分:首先将列表按字母顺序排序。将此新文件另存为answer目录中的p4aNames.txt。
第2部分:使用p4aNames.txt,取每个名称的字母值,并将此值乘以列表中的字母位置以获取名称分数。例如,当列表按字母顺序排序时,值为3 + 15 + 12 + 9 + 14 = 53的COLIN是列表中的第938个名称。因此,COLIN将获得938×53 = 49714的分数。将所有名称分数列表保存为p4bNames.txt。
第3部分:文件中所有名称分数的总和是多少?
Pic Link显示输出&目录:
http://screencast.com/t/tiiBoyOpR
我当前的代码:
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 appearingbeforefirstname
// System.out.println(out); // output:
// "MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER","MARIA"...
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
int score = 0;
// sortedStr[i].replaceAll("\"", ""); // I used this to try to remove the "s from my Strings
for (char ch: sortedStr[i].toUpperCase().toCharArray()) {
score += ((int)ch - 64); /* A is decimal 65 */
}
score = score * i; /* multiply by position in the list */
pw.println(score);
System.out.println(score);
}
bf.close();
fb.close();
pw.close();
}
}
答案 0 :(得分:0)
你写了
// sortedStr[i].replaceAll("\"", ""); // I used this to try to remove the "s from my Strings
Java String
是不可变的。该函数返回一个删除了引号的新字符串。你可以使用
sortedStr[i] = sortedStr[i].replaceAll("\"", "");
它应该可以正常工作。