-
Random lowercase letter
I need to generate a random lowercase letters to be written to file.
Here is the code I have so far:
Code:
public static void main(String[] args) throws Exception {
Random r = new Random();
// Write data to file.
PrintWriter data = new PrintWriter("Ex19.txt");
for (int i = 0; i < 50; i++)
data.print((char)((r.nextInt(26) + 'a')) + " ");
data.close();
}
This code is writing weird characters to file. E.g.:
⁶⁺⁵⁰⁰⁷⁰⁸⁹⁷⁶⁷⁹⁴⁶⁺⁺⁹⁴ⁱ ⁱ
What is throwing me off is that changing the code to Code:
data.print((r.nextInt(26) + 'a') + " ");
appears to write the correct range of numbers to file (i.e. between 97 & 122).
Can someone please help me?
-
I don't know. This code seems to work OK for me:
Code:
Random r = new Random();
// Write data to file.
// PrintWriter data = new PrintWriter("Ex19.txt");
for (int i = 0; i < 50; i++) {
System.out.print((char) ((r.nextInt(26) + 'a')) + " ");
}
System.out.println();
edit:
and then when I tried your code with the PrintWriter, I got this as an output:
o q c v k r a h s o r v k z z k y j h l a r t w h f i z f d h b d q f i c o b w t y z n g i j u c t
So it looks good to me! Are you sure you're looking in the correct file?
-
After reading this text file back into the program and getting legitimate characters, I opened the text file using WordPad (instead of Notepad) and the characters are ok!
Must be some weird Windows thing....
http://oi55.tinypic.com/2qvrwq1.jpg
-
Good deal! Keep up the good work!