我将以下代码作为星球大战名称生成器的一部分。
我唯一能弄清楚如何做的就是添加一个力数,这需要将星球大战名称转换为其编号对应物(A = 1,B = 2 ... Z = 26等。),然后将这些数字加在一起,形成一个最终数字(强制数字)。
我已经对我认为获得力数的部分进行了评论,但它仍然会产生错误。
另外,我得到的这个字母到数字转换代码来自另一个帖子,而且它不是执行任务的最有效方法。
感谢您的帮助。
import java.util.Scanner;
import static java.lang.System.out;
public class starWarsName {
private static final Scanner INPUT = new Scanner(System.in);
public static void main(String args[]) {
out.println("Star Wars name and force # Generator");
String firstName = promptString("State your first name: ");
String lastName = promptString("State your last name: ");
String maiden = promptString("Enter your mother's maiden name: ");
String city = promptString("Enter the city/town in which you were born: ");
while(lastName.length() < 3)
lastName += lastName;
while(firstName.length() < 2)
firstName += firstName;
while(maiden.length() < 2)
maiden += maiden;
while(city.length() < 3)
city += city;
String swFirstName = (lastName.substring(0,3) + firstName.substring(0,2)).toUpperCase();
String swLastName = (maiden.substring(0,2) + city.substring(0,3)).toUpperCase();
//*
import java.util.HashMap;
import java.util.Map;
final Map<Character, Integer> map;
final String str = "forceNum = ";
map = new HashMap<>();
map.put('a', 1); map.put('b', 2); map.put('c', 3); map.put('d', 4); map.put('e', 5); map.put('f', 6); map.put('g', 7); map.put('h', 8); map.put('i', 9); map.put('j', 10); map.put('k', 11); map.put('l', 12); map.put('m', 13); map.put('n', 14); map.put('o', 15); map.put('p', 16); map.put('q', 17); map.put('r', 18); map.put('s', 19); map.put('t', 20); map.put('u', 21); map.put('v', 22); map.put('w', 23); map.put('x', 24); map.put('y', 25); map.put('z', 26);
for(final char c : str.toCharArray())
{
final Integer val;
val = map.get(c);
if(val == null)
{
}
else
{
System.out.print(val + " ");
}
}
System.out.println();
}
}
//*
out.println("Your Star Wars name is " + swFirstName + " " + swLastName + " with a force # of " + forceNum);
}
private static String promptString(String prompt) {
out.print(prompt);
return INPUT.nextLine().trim();
}
}
答案 0 :(得分:0)
您的“部队名称”将是string
,由chars
组成。每个char
都有一个整数ASCII
值(例如'A' = 65, 'B' = 66, 'a' = 97, 'z' = 122
)。您可以使用'A'
和'a'
的值作为“起点”为每个字母分配字母数字。
即,字母'A'将是65 - 65 + 1 = 1
。同样,字母'B'(66 - 65 + 1 = 2
),字母'a'(97 - 97 + 1 = 1
)和字母'z'(122 - 97 + 1 = 26
)。
String name = "First Middle Last"; // this implementation ignores spaces
int sum = 0; // store the accumulating force number
for (int i = 0; i < name.length(); ++i) { // iterate over name, one letter at a time
int letter = name.charAt(i);
if (letter >= 'A' && letter <= 'Z') {
sum += letter - 'A' + 1; // capital letters use 'A' as starting point
} else if (letter >= 'a' && letter <= 'z') {
sum += letter - 'a' + 1; // little letters use 'a' as starting point
}
}
System.out.println(sum); // verify sum is 72 + 47 + 52 = 171