0

I am trying to go through a string one character at a time and change those characters into their ASCII numbers. I have it working wine except for the spaces in the text turned into '' (with no space) instead of ' ' (with space).

Scanner in = new Scanner(original_file);
PrintWriter out = new PrintWriter("encoded_message.txt");
text_file = "";
while (in.hasNextLine()) {
    text_file += in.nextLine() + "\n";
}
char[] text_file_array = text_file.toCharArray();
for (char c : text_file_array) {
    int code = Character.getNumericValue(c); //<-- The problem is here.
    out.println(code);
}
in.close();
out.close();

When I run this, the c becomes '' which makes code have a value of -1. I later use code in an array. How do I make it return ' '?

ToMakPo
  • 855
  • 7
  • 27

1 Answers1

1

The Character.getNumericValue() method returns the unicode numeric value not the ASCII value.

e.g. for 'e' ASCII is 101, unicode is 14.

ASCII is relatively simple:

int ascii = (int) character;

Convert character to ASCII numeric value in java

The javadoc for getNumericValue discusses this but sheds little light to the matter:

https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#getNumericValue%28char%29

The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

If the character does not have a numeric value, then -1 is returned. If the character has a numeric value that cannot be represented as a nonnegative integer (for example, a fractional value), then -2 is returned.

The c doesn't in fact change to become '' (with no space). If you change your out.println method to this (debugging, yes? you can clean it up later), you can get more info:

out.println("'" + c + "'" + "  " + code + "  " + (int)c);
Community
  • 1
  • 1
GregHNZ
  • 7,946
  • 1
  • 28
  • 30