二维数组现在是纯粹的参考。我需要知道如何用相应的整数替换字符串中的字符并以双格式显示它。
例如,根据conversionTable
---> [Input: "ab.a" , Output: "1.0"]
或[Input: "a.jjj" , Output: "0.999"]
。我试图通过开关盒实现这一点,但它给出了错误。如何通过开关盒或更高效地实现这一目标?
package practice;
import java.util.Scanner;
import java.lang.Double;
public class Decrypt {
private static String conversionTable[][] = {
{"a", "0"},
{"b", "1"},
{"c", "2"},
{"d", "3"},
{"e", "4"},
{"f", "5"},
{"g", "6"},
{"h", "7"},
{"i", "8"},
{"j", "9"},
};
public static double decrypt(String encryptedNumber) {
String input = encryptedNumber;
switch(input.length()){
case 'a':
System.out.print(input.replace('a', '0'));
break;
case 'b':
System.out.print(input.replace('b','1'));
break;
case 'c':
System.out.print(input.replace('c', '2'));
break;
case 'd':
System.out.print(input.replace('d','3'));
break;
case 'e':
System.out.print(input.replace('e','4'));
break;
case 'f':
System.out.print(input.replace('f','5'));
break;
case 'g':
System.out.print(input.replace('g','6'));
break;
case 'h':
System.out.print(input.replace('h','7'));
break;
case 'i':
System.out.print(input.replace('i','8'));
break;
case 'j':
System.out.print(input.replace('j','9'));
break;
}
Double d = new Double("");
double result = Double.parseDouble(input);
return result;
}
public static void main(String arg[]){
Scanner scanner =new Scanner(System.in);
System.out.println("Enter the string to decrypt:");
String input=scanner.next();
System.out.println("Number after decryption is:"+decrypt(input));
}
}
答案 0 :(得分:0)
我会使用(char) ('0' + (ch - 'a'))
的东西,因为我们知道'a'是'a',而'b' - 'a'应该是'1'。例如,
private static String decryptString(String en) {
if (en == null) {
return "";
}
en = en.trim().toLowerCase();
StringBuilder sb = new StringBuilder();
for (char ch : en.toCharArray()) {
if (ch >= 'a' && ch <= 'j') {
sb.append((char) ('0' + (ch - 'a')));
} else {
sb.append(ch);
}
}
return sb.toString();
}
public static Double decrypt(String encryptedNumber) {
return Double.valueOf(decryptString(encryptedNumber));
}
public static void main(String[] args) {
System.out.println(decrypt("ab.a"));
System.out.println(decrypt("a.jjj"));
}
输出(按要求)
1.0
0.999
答案 1 :(得分:0)
写一个非常难看的人:
public static void main(String[] args) {
String[] index = {"a","b","c","d","e","f","g","h","i","j"};
String str= "ab.a";
String strNew = str;
for(int i=0;i<index.length;i++){
strNew = strNew.replaceAll(index[i], String.valueOf(i));
}
System.out.println(Double.parseDouble(strNew));
}