简体   繁体   中英

Java - convert string of letters to a string of digits

I'm trying to learn Java but I'm stuck at an exercise: I have to write a "decrypt()" method, that converts a String like b.aab and returns to double value 1.001.

I'm also given a 2 dimensional array of characters and the number they represent.

private static String conversionTable[][] = {
        {"a", "0"},
        {"b", "1"},
        {"c", "2"},
        {"d", "3"},
        {"e", "4"},
        {"f", "5"},
        {"g", "6"},
        {"h", "7"},
        {"i", "8"},
        {"j", "9"},
};

I know there is technique to convert a char ch into a digit with its ascii value, something like ch -'a' + 1, but I'm not sure how to apply this here. So my question is: How can I convert a String of letters to String of corresponding digits? From there I would use parseDouble(); to return a double of the String. Thank you in before.

You should try like this

char ch='A';
int value=(int)ch-17;
System.out.println(value);
import java.util.Scanner;

public class Program10 {

         public static void main(String[] args) {

                System.out.println("Enter a string to decrypt");
                Scanner sc = new Scanner(System.in);
                String input = sc.nextLine();

              decrypt(input);
    }

      public static void decrypt(String input) {

          char ch;
          String str = "";
          int length = input.length();

         for(int i = 0; i < length ; i++) {

                ch = input.charAt(i);

                   if(ch != '.') {  
                     int val = (int) ch;
                    str = str + (val - 97); 
                  } else {

                     String x = "" + ch;
                     str = str.concat(x);
                }

         }
         System.out.println(str);
}

}

This does the trick using Java8:

public static void main(String args[]){
    String t="abcd";
    for(String s:t.split("")){
        System.out.println(s.charAt(0)-'a');
    }
}

If it is all lowercase, you could make use of the fact, that 'a'-'a'=0. Using Java4-7 you have to skip the empty char.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM