Reading a text file word by word
Hi all, new to Java programming. Got into it, cause a friend also has been doing it, but he's been doing it for a while, so is really good. Anyways.
So what I want to do it, read a specific .txt file, then go through that, and split it into words. If that makes sense.
What I want the program to do, is, go through a file, and identify and count how many palindromes are inside the file. So I have been able to do the palindrome part of it. But I am just confused as to how you go about reading the text, word for word, then testing it out.
And help will be appreciated, and not in a rush, this is just a hobby, that I am really enjoying :D
Re: Reading a text file word by word
Here is the first hit after googling "java file io": Lesson: Basic I/O (The Java™ Tutorials > Essential Classes)
But this sounds like a job for the Scanner class. The API is your new best friend: Java Platform SE 6
Re: Reading a text file word by word
OK, hi again. I ended up figuring out how to do it. But I have a new problem. When I run the program, I want it to only find single word palindromes. At the moment, when I do it, it is also getting multiple word palindromes. So, in a text file I have, it has, for example "avid diva". It is coming up that each of these are palindromes. And I want it too be only one word palindromes, for example "otto". Any help again is appreciated. Here is what I currently have :D
Code :
import java.io.*;
public class PalindromDetector {
public static void main(String[] args) {
try {
FileInputStream fstream = new FileInputStream("C:/Test1.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
while ((strLine = br.readLine()) != null) {
String reverse = new
StringBuffer(strLine).reverse().
toString();
int i,j,counter=0;
String m[]=strLine.split(" ");
String[] word=reverse.split(" ");
System.out.println("The palindrome words are:");
for(i=0;i<m.length;i++) {
for(j=word.length-1;j>=0;j--) {
if(m[i].equalsIgnoreCase(word[j])) {
System.out.println(m[i]);
counter++;
break;
}
}
}
System.out.println("Number of palindromes:"+counter);
}
}
catch(IOException e){}
}
}
Dunno what I have done. Obviously something silly. I'm sure what I have done is supposed to be harder that what I am supposed to have done :P
Re: Reading a text file word by word
Instead of taking the file one line at a time, why don't you take it one word at a time, since that's what you really care about?