This discussion is archived
1 2 Previous Next 17 Replies Latest reply: Oct 1, 2008 5:18 PM by 3004 RSS

Help with String Tokenizer!  Urgent!

843785 Newbie
Currently Being Moderated
I have to make a program which takes all these words from a file and tells you weather they can be spelt the same backwards and forwards, and i just cannot get it to work. what is wrong with my program?

import java.io.*; // Neeeded for IOException.
import java.util.StringTokenizer; // Needed for StringTokenizer.
import javax.swing.JOptionPane; // Needed for JOptionPane.

public class TokenizerClass
{
public static void main(String[] args) throws IOException
{
boolean palindrome = false; // True or false palindrome
double counter = 0.0; // How many times true
double counter2 = 0.0; // How many times false
double percentage = 0.0; // Percent of palindromes

// Get the file to be analyzed.
FileReader fRead = new FileReader("as1q4.txt");
BufferedReader file = new BufferedReader(fRead);

// Get the first line of the file.
String line = file.readLine();

// Tokenize the first line of the String
StringTokenizer tokener = new StringTokenizer(line);

while (line != null)
{
boolean yesno = false;
yesno = tokener.hasMoreTokens();
if (yesno == true)
{
JOptionPane.showMessageDialog(null, "has more tokens..");
// Uses the token in the string
palindrome = isPalindrome(tokener.nextToken());
}

// If the word is a palindrome...
if (palindrome == true )
{
// Adds one to the accumulator for the
// calculation of percentage.
counter ++;
break;
}
// if the word is not a palindrome...
else
{
// Adds one to the accumulator for the
// calculation of percentage.
counter2++;
}
line = file.readLine();

}
// Close the file
file.close();

JOptionPane.showMessageDialog(null, counter + " " + counter2);
// Calculate the percentage of palindromes in the file.
percentage = counter / (counter + counter2) * 100;
JOptionPane.showMessageDialog(null, "The words are " +
percentage + "% palindromes");
}

/**
* The isPalindrome method returns a true or false value of
* if the word evaluated was a palindrome or not.
* @param inputWord the word to be evaluated.
* @return If the word is true or false.
*/

public static boolean isPalindrome(String inputWord)
{
boolean pal = true; // If palindrome is true or false

// Check if the word is a palindrome.
for (int i = 0; i < inputWord.length() / 2; i++)
{
// If word is not palindrome change "pal" to false.
if (!(inputWord.charAt(i) ==
inputWord.charAt(inputWord.length() - i - 1)))
{
pal = false;
break;
}
if (i == inputWord.length() / 2 - 1)
{
return true;
}
}return false;
}
}
1 2 Previous Next