Hi all,

I am trying to take a list of words (from a text file) and then split each word into characters how can I do this?

The code I currently have just reads in all the words (at, as, ate, apple, apply) found in text file and prints them out (as many times as the length of the word). What I really want is for my program to take one word from the text file and split it into characters on one line in the output. Would I have to save the words from the text file in an array first?

My code:

import java.io.*;


class FileReadTest {


public static void main (String[] args) {
FileReadTest t = new FileReadTest(); //creates object of the class
t.readMyFile(); //applies the readMyFile method to the object
}


void readMyFile() {
String record = null;  //initialises the string variable record to null


try {
FileReader fr = new FileReader("C:\\Documents and Settings\\sumiya\\My Documents\\Scrabble Project\\scrabbledict.txt");
//creates a new filereader for the named file in the arguments
BufferedReader br = new BufferedReader(fr);


record = new String();
while ((record = br.readLine()) != null) {
System.out.println(record);


for(int i=0; i<record.length(); i++){
record.charAt(i);
System.out.println("Character at i = " +record);
}


}
} catch (IOException e) {
// catches possible io errors from readLine()
System.out.println("Uh oh, got an IOException error!");
e.printStackTrace();
}
}


} // end of class

Edited 3 Years Ago by happygeek: fixed formatting

You could use a StringTokenizer to read everything that's a word(doesn't read white space).
Get the length of the word.
In a for loop you can process the char at index 'i' by using charAt(i).

String record = null;

I'd recommend changing that to String record; . Once you create a String, even if it's null, you can't change it - they're immutable. String record; will tell the app that a String called record will be created, but not actually create it until you do record = something .

As for your actual question:

What I really want is for my program to take one word from the text file and split it into characters on one line in the output.

String.toCharArray(); ?

This question has already been answered. Start a new discussion instead.