سؤال

I'm working on an assignment for my programming class but I've run into some difficulty and I'm not sure where else to look. Basically the question asks that we write a program that checks for palindromes.

  • The user enters text (No non-alphanumberic chars allowed.)
  • The String is pushed one character at a time into a stack
  • The characters are pulled one at a time out of the stack thus reversing the String
  • If the original is the same as the reverse, we have a palindrome

I'm having some trouble with my loops though and don't know where to go from here, does anyone have any advice or pointers? What am I doing wrong?

Here's what I have so far.

import java.util.Stack;
import java.util.regex.*;
import javax.swing.*;

public class Question1 {

    static Stack PDrome = new Stack();

    public static String Reverse (String input) {
        String reverse;

        if (input.length() <= 1) {
            return input;
        }   

        //pushing onto the stack
        for (int i=0; i<input.length();i++) {
            PDrome.push(input.charAt(i));
        }


        //popping from the stack into the string
        for (int i=0; i<input.length(); i++) {  
            PDrome.pop()=reverse.charAt(i);
        }  

        return reverse;
    }

    //Illegal char check method
    public static boolean checker (String input) {
        Pattern p = Pattern.compile("[^a-z0-9]", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(input);
        boolean b = m.find();

        if (b) {
            System.out.println("There is a special character in your string");   
            System.exit(0);
        }   

        return b;    
    }


    //Main
    public static void main (String [] args) {
        //input
        String input = JOptionPane.showInputDialog("Enter text to check if it's a palndrome");

        //error case
        if (input==null); {
            System.out.println("Nothing Entered");
            System.exit(0);
        }

        //checking for illegal chars
        checker(input);
    }
}
هل كانت مفيدة؟

المحلول

This part:

String reverse;
...
//popping from the stack into the string
for (int i=0; i<input.length(); i++)
{   
    PDrome.pop()=reverse.charAt(i);
}  

should be like this:

String reverse = "";
...
//popping from the stack into the string
for (int i=0; i<input.length(); i++)
{   
    // appends the popped character to reverse
    reverse += PDrome.pop();
}  

note that when appending a large number of string, this isn't the best way to do it since Java's string is immutable and repeatedly appending a string would require creating a new string each time. This problem is small enough that it wouldn't really matter though, but when the problem gets large you'll want to use StringBuffer/StringBuilder.

نصائح أخرى

PDrome.pop()=reverse.charAt(i); is wrong.

  1. reverse is null -> NullPointerException
  2. Are you assigning a value to a function? (pop())

You have to build reverse from pop'ping from the stack.

So you should start with an empty string: reverse = ""; and add the chars taken from the stack:

while (!PDrome.isEmpty())
   reverse += PDrome.pop();

Naming detail

Please use non capital letters to start fields and method names:

"someIntegerVariable"
"methodForCalculation"

and only capital letters to start class and interface names:

Stack
ArrayList
MyClass

:)

(from the Java conventions)

What are you actually doing here?

PDrome.pop()=reverse.charAt(i);

You should have use PDrome.pop() to retrieve one char at a time and append it to reverse.

This is a much cleaner way to write it in my opinion. It is a recursive approach.

bool isPalindrome(String s)
{
    if(s.length() <= 1)
        return true;

    return s[0] == s[s.length() - 1] && isPalindrome(s.substr(1, s.length() - 2);
}

It is MUCH shorter as you can see.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top