mrvrs123 mrvrs123 - 4 months ago 17
Java Question

octal value of String

I need octal value of any given string, for that I am using below code.

public static void main(String[] args) {

HashMap<Character, String> octalValues = new HashMap<Character, String>();
octalValues.put('*', "052");
octalValues.put('1', "061");
octalValues.put('2', "062");
octalValues.put('3', "063");
octalValues.put('a', "141");
octalValues.put('b', "142");
octalValues.put('c', "143");
octalValues.put('d', "144");

String value = "123abc*";

for (char i = 0; i < value.length(); i++) {
System.out.print(octalValues.get(value.charAt(i)) + " ");
}


output : 061 062 063 141 142 143 052

Is there any predefined Java method or sorter that can be used for this?

Answer

use Integer.toOctalString(int)

I'd say, split them into characters, cast character to an Integer and then create an octal string out of that. Like Integer.toOctalString((int) 'c'). This first turns your character into an Integer, then it creates a Stringrepresentation of the octal value of your character.

So in your example, if you have a String, you can do this for each character in the string. You do not have to cast explicitely for this. (Just keep in mind that a character can be represented as an integer, but we are not doing this ourselves here)

 String s = "Hello World";
 for(int i = 0; i < s.length(); s++){
    String octalString = Integer.toOctalString(s.charAt(i));
 }

There is a second 'mistake'

You are using a character as the datatype to loop. Whilst that actually does work, it's not the right datatype for indexing your loops. When you write a loop over the length of a string, you are using integers. The integer in the loops denotes the index. In this case, indeed, the index refers to a character in your String, but that just holds in this case. When I would read that code, I would expect you to do something with the characterthat you created in the loop. Not just use it as an index for the String.