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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With