2014-07-08 93 views
-1

2維數組是純粹參考的。我需要知道如何用相應的整數替換字符串中的字符並以雙重格式顯示它。例如conversionTable --->[Input: "ab.a" , Output: "1.0"][Input: "a.jjj" , Output: "0.999"]。我試圖實現這個通過開關的情況下,但它會給出錯誤。我怎樣才能實現這個直通開關案例或更有效?如何替換字符串中的字符並將其轉換爲double?

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)); 

} 

} 
+1

「但它給出了一個錯誤。」你收到什麼錯誤?完整的堆棧跟蹤是首選,因爲我們可以確切地看到*錯誤是什麼以及*發生了哪裏。 –

回答

0

我會使用與(char) ('0' + (ch - '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 
+0

完美,你能解釋一下(char)(0+(ch-a)背後的邏輯嗎?爲什麼我們基本上加減0? – user3802928

+0

不是'0',它是'0',這是ASCII字符' 0'。如果你看看ascii字符表,你會發現'b'是一個過去的'a',比'c'小一個等等。無論如何,當轉換爲'int''0'是48,'a'是97. –

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)); 
} 
+1

可能我們需要考慮小寫和大寫,沒關係,只需在解密之前切換到小寫。 – KingQQ

相關問題