Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.text.*;
- import javax.swing.*;
- import java.util.*;
- import java.util.Scanner;
- import java.util.Stack;
- public class palindromes {
- public static void main(String[] args) {
- Scanner infile = new Scanner (System.in);
- String s = "";
- int StrLength;
- while (!s.equals("Q"))
- {
- // Explains what a palindrome is and asks user to enter test phrase.
- System.out.println("This program will test strings to see if they are palindromes.");
- System.out.println("A palindrome is a word or phrase that is spelled the same way frontwards and backwards.");
- System.out.println("Please enter a string to be tested (Enter 'Q' to quit): ");
- // User enters test phrase. If phrase == 'Q', program ends.
- s = infile.next();
- // Converts all letters to caps, removes all white-space and punctuation,
- // initializes and stores the value of the length of String 2, initializes the stack.
- s.toUpperCase();
- s.replaceAll("\\W", "");
- s.replaceAll("\\s", "");
- StrLength = s.length() - 1;
- Stk s2 = new Stk(s.length());
- int i;
- // Pushes every letter in the string into the stack.
- for (i = 0; i <= StrLength; i++) {
- s2.push(s.charAt(i));
- };
- char c;
- i = 0;
- // While S3 is not empty, compare popped character with character in same position in string.
- // If both are equal, continue until s3 is empty. If there is any difference, end the loop.
- while (!s2.isEmpty()) {
- c = s2.pop();
- if (c == s.charAt(i)) {
- i++;
- if (i > StrLength) {
- System.out.println("This string is a palindrome. Please enter another string to test (Enter Q to quit).");
- s = infile.next();
- StrLength = 0;
- };
- }
- else
- {
- System.out.println("This string is not a palindrome. Please enter another string to test (Enter Q to quit).");
- s = infile.next();
- StrLength = 0;
- };
- };
- };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement