I am trying to create a program which will read a file and check whether the text is a palindrome or not. The code compiles, but doesnt really work.
The problem is I dont know how to break a complete token into characters or assign it to a string in order to use string's length to push
(enqueue) each letter or digit into the stack
(queue). Can anyone suggest a solution for this?
public static void main(String [] args) throws IOException{
StackReferenceBased stack = new StackReferenceBased();
QueueReferenceBased queue = new QueueReferenceBased();
Scanner s = null;
String fileName=args[0]+".txt";
int symbols = 0;
int lettersAndDigits =0;
int matches = 0;
try{
s = new Scanner(new File(fileName));
while(s.hasNext()){
String current = s.next();
for(int i=0;i<current.length();i++){
char temp = s.next().charAt(i);
if(Character.isLetterOrDigit(temp)){
stack.push(temp);
queue.enqueue(temp);
lettersAndDigits++;
}
else {
symbols++;
}
}
}
System.out.println("There are: " + " "+ symbols + " " +"symbols and " + " "+lettersAndDigits + " "+ "digits/letters");
}
catch (FileNotFoundException e) {
System.out.println("Could not open the file:" + args[0]);
} //catch (Exception e) {
//System.out.println("ERROR copying file");
finally {
if(s != null){
s.close();
}
}
while (!stack.isEmpty()){
if(!stack.pop().equals(queue.dequeue())){
System.out.println("not pali");
break;
}
else {
++matches;
}
}
if(matches==lettersAndDigits){
System.out.print("pali");
}
}
Instead of
char temp = s.next().charAt(i);
you need
char temp = current.charAt(i);
By calling s.next()
you read the next token from the file and try to access the i
th element of that token based on the first string's (current
) length, which will lead to exceptions if the tokens read are shorter than the first stoken