0

Refer to Converting Letters to Numbers

In the file test.in.rtf, I have 'abcd' typed. However, when I run the program, I get ??? ??????????? ???????? plus maybe a few more in test.out.rtf. Why is this? Am I missing something?

import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; public class Test { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader("test.in.rtf")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test.out.rtf"))); StringTokenizer st = new StringTokenizer(f.readLine()); StringBuilder sb = new StringBuilder(); for (char c : st.nextToken().toCharArray()) { sb.append((char)(c - 'a' + 1)); } out.println(sb); // output result out.close(); // close the output file System.exit(0); } } 
5
  • I am trying to convert letters to numbers where a = 1, b = 2, c = 3, d = 4, z = 26... Commented May 18, 2012 at 22:35
  • 1
    debugging is part of the fun :) Commented May 18, 2012 at 22:44
  • RTF files are binary files. You can't process them like string data. Commented May 18, 2012 at 22:53
  • @skaffman They're not binary. It's a markup language, which you could parse, it's just not very trivial. Commented May 18, 2012 at 22:55
  • @trutheality: Good point. My mistake. Commented May 18, 2012 at 22:56

2 Answers 2

2

I'm pretty sure you want

sb.append(Integer.toString(c - 'a' + 1)); 

or simply

sb.append( c - 'a' + 1 ); 

which implicitly does the same thing, since the expression c - 'a' + 1 is implicitly cast to an int since Java does all non-long integer math (anything involving chars, bytes, shorts, and/or ints) by converting everything to ints first.

What you had cast the integer result to a char, which would be represented by the character whose ASCII value is that number (something b/w 1 and 26), which isn't something readable.

Sign up to request clarification or add additional context in comments.

2 Comments

No, I get 27-418206-47-4114199-41141993167-47-46-43-46-4315315118206-47-48-45-40-431531511921218206-45-43-48 somehow.
Is test.in.rtf a Rich Text Format file by any chance? Because this will only work for a text file.
1

You are trying to write the char values 1,2,3 and 4 ('a'-'a' + 1 = 1 and so on), which are all "unwriteable" hence the "?"s. Why you get 7 and not 4? I don't know - maybe a locale issue or 3 of them are just written as two "?".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.