我试图将一个将你的名字改成数字的东西编码,而且我不确定我是不是最简单甚至最直接的方式。我对编程很陌生。
public class Project1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
char ch1 = 'a';
char ch2 = 'b';
char ch3 = 'c';
char ch4 = 'd';
char ch5 = 'e';
char ch6 = 'f';
char ch7 = 'g';
char ch8 = 'h';
char ch9 = 'i';
char ch10 = 'j';
char ch11 = 'k';
char ch12 = 'l';
char ch13 = 'm';
char ch14 = 'n';
char ch15 = 'o';
char ch16 = 'p';
char ch17 = 'q';
char ch18 = 'r';
char ch19 = 's';
char ch20 = 't';
char ch21 = 'u';
char ch22 = 'v';
char ch23 = 'w';
char ch24 = 'x';
char ch25 = 'y';
char ch26 = 'z';
int num1 = ch1 - 'a' + 1;
int num2 = ch2 - 'a' + 1;
int num3 = ch3 - 'a' + 1;
int num4 = ch4 - 'a' + 1;
int num5 = ch5 - 'a' + 1;
int num6 = ch6 - 'a' + 1;
int num7 = ch7 - 'a' + 1;
int num8 = ch8 - 'a' + 1;
int num9 = ch9 - 'a' + 1;
int num10 = ch10 - 'a' + 1;
int num11 = ch11 - 'a' + 1;
int num12 = ch12 - 'a' + 1;
int num13 = ch13 - 'a' + 1;
int num14 = ch14 - 'a' + 1;
int num15 = ch15 - 'a' + 1;
int num16 = ch16 - 'a' + 1;
int num17 = ch17 - 'a' + 1;
int num18 = ch18 - 'a' + 1;
int num19 = ch19 - 'a' + 1;
int num20 = ch20 - 'a' + 1;
int num21 = ch21 - 'a' + 1;
int num22 = ch22 - 'a' + 1;
int num23 = ch23 - 'a' + 1;
int num24 = ch24 - 'a' + 1;
int num25 = ch25 - 'a' + 1;
int num26 = ch26 - 'a' + 1;
String name = JOptionPane.showInputDialog(null,"Enter your name:");
System.out.println("your name is: " +name);
}
}
答案 0 :(得分:0)
试试这个
String name = "abc";
char[] chars = name.toCharArray();
for (char c : chars) {
System.out.print(c-'a'+1);
}
答案 1 :(得分:0)
您可以更轻松地完成此任务。
由于您没有说 如何将字符串转换为数字/数字。我会给你一些选择。
首先,您可以使用hashCode
。此方法为每个唯一字符串返回唯一值:
String name = JOptionPane.showInputDialog(null,"Enter your name:");
System.out.println("your name is: " + name.hashCode());
所以,如果我进入" Sweeper"和" Sweeper",输出将是相同的:
your name is: -143341447
或者,您可以将char
转换为int
,将每个字符转换为相应的ASCII代码:
String name = JOptionPane.showInputDialog(null,"Enter your name:");
char[] chars = name.toCharArray();
System.out.print("your name is: ");
for (char c : chars) {
System.out.print((int)c);
System.out.print(" ");
}
进入"清扫工"将输出:
your name is: 83 119 101 101 112 101 114
另一种方法是添加ASCII值:
String name = JOptionPane.showInputDialog(null,"Enter your name:");
char[] chars = name.toCharArray();
System.out.print("your name is: ");
int sum = 0;
for (char c : chars) {
sum += (int)c;
}
System.out.println(sum);
"清扫"输入将产生:
your name is: 731
您还可以在HashMap<Character, Integer>
中添加a-z和A-Z,为每个角色提供自定义值:
HashMap<Character, Integer> map = new HashMap<>();
map.put('a', 1);
map.put('b', 2);
map.put('c', 3);
map.put('d', 4);
map.put('e', 5);
// and so on...
String name = JOptionPane.showInputDialog(null,"Enter your name:");
char[] chars = name.toCharArray();
System.out.print("your name is: ");
for (char c : chars) {
System.out.print(map.get(c));
System.out.print(" ");
}