我正在为我的编程课做作业,但我遇到了一些困难,我不知道还能去哪里找。基本上,这个问题要求我们编写一个检查回文的程序。
- 用户输入文本(不允许使用非字母数字字符。)
- 将字符串一次一个字符压入堆栈
- 字符从堆栈中一次拉出一个,从而反转字符串
- 如果原件和反件相同,我们有一个回文
我的循环遇到了一些问题,不知道从哪里开始,有没有人有任何建议或指示?我究竟做错了什么?
这是我到目前为止所拥有的。
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);
}
}